[英]Is there a way to center both a label and entry box on a specific row in tkinter?
我正在尝试使用Python(Tkinter)设计屏幕,在对问题进行了彻底研究之后,我无法找到一种方法将“标签”和“输入”框同时放在屏幕上我想要的行中。 需要明确的是,我不希望它位于屏幕的中心,而是希望位于我选择的行的中心。
我已经尝试过.pack()的一些方法,并使用网格来做到这一点,但似乎什么也做不了。
我像这样设置根:
root = tk.Tk()
我这样设置GUI的宽度和高度:
screen_width = str(root.winfo_screenwidth())
screen_height = str(root.winfo_screenheight())
root.geometry(screen_width + "x" + screen_height)
然后按如下所示设置标签及其输入框的位置:
fName = tk.Label(root, text="First Name")
fName.grid(row=0)
lName = tk.Label(root, text="Last Name")
lName.grid(row=1)
ageLabel = tk.Label(root, text="Age")
ageLabel.grid(row=2)
correctedLabel = tk.Label(root, text="Is your vision, or corrected to, 20/20? (Y/N)")
correctedLabel.grid(row=3)
genderLabel = tk.Label(root, text="Gender")
genderLabel.grid(row=4)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e3 = tk.Entry(root)
e4 = tk.Entry(root)
e5 = tk.Entry(root)
root.winfo_toplevel().title("Information Collection")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
e5.grid(row=4, column=1)
使用当前的代码,它将从Tkinter获取屏幕的宽度和高度,并将窗口大小调整为屏幕大小。 同样使用此代码,有人会看到有4个标签及其对应的输入框,我想将每组标签及其输入移动到其行的中心。 我将不胜感激。
您可以从设置grid
的weight
开始,该weight
将调整应占据的每一行/列的权重:
root.grid_columnconfigure(0,weight=1)
root.grid_columnconfigure(1,weight=1)
现在,您应该看到左右标签均均匀地分布在整个屏幕上,这正是您想要的。 如果您想以某种方式使它们正确居中,则可以将sticky
方向应用于小部件。
fName.grid(row=0,sticky="e")
...
e1.grid(row=0, column=1,sticky="w")
...
完整样本:
import tkinter as tk
root = tk.Tk()
root.title("Information Collection")
root.geometry(f"{root.winfo_screenwidth()}x{root.winfo_screenheight()}")
labels = ("First Name","Last Name","Age","Is your vision, or corrected to, 20/20? (Y/N)","Gender")
entries = []
for num, i in enumerate(labels):
l = tk.Label(root, text=i)
l.grid(row=num, column=0, sticky="e") #remove sticky if not required
e = tk.Entry(root)
e.grid(row=num, column=1, sticky="w") #remove sticky if not required
entries.append(e) #keep the entries in a list so you can retrieve the values later
root.grid_columnconfigure(0,weight=1)
root.grid_columnconfigure(1,weight=1)
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.