在 tk 中将文本居中放置在按钮中

centering a text within a button in tk

通常 tkinter 中的按钮会自动将其文本居中,但我似乎无法理解,我不知道为什么!

from tkinter import *
from tkinter import messagebox
from PIL import Image,ImageTk
from getpass import getpass
huh=Tk()
huh.title('Login page')
huh.configure(bg='white')
huh.resizable(False,700)
huh.geometry('925x500+300+200')
my_fr=Frame(huh,width=350,height=350,bg='white')
my_fr.place(x=480,y=90)
btn=Button(my_fr,width=50,border=0,text="Connexion",bg='#000000',fg="#ffffff",font='Railway',anchor=CENTER)
btn.place(x=43,y=300)
huh.mainloop()

这是一个使用 grid() 的解决方案,该解决方案将文本居中放置在与原始 place() 语句一起使用的 x、y 坐标处。

请注意,resizeable() 仅采用布尔参数,因此“700”将被解释为 True。假设最大 window 高度为 700,最小高度为 500 是意图,resizeable() 被替换为 minsize()maxsize() 语句。

保留了geometry()语句,但是如果系统默认的window位置合适,那么可以去掉

my_fr.grid() 替换为 my_fr.pack() 会使按钮水平居中,从而忽略 padx 规范。

import tkinter as tk

huh = tk.Tk()
huh.title('Login page')
huh.configure(bg='white')

huh.geometry('925x500+300+200')
huh.minsize(925, 500)
huh.maxsize(925, 700)

my_fr = tk.Frame(huh, bg='white')
btn = tk.Button(my_fr, width=50, text="Connexion",
                bg='black', fg="white", font='Railway')

my_fr.grid()
btn.grid(padx=43, pady=300)

huh.mainloop()