簡體   English   中英

是否可以在tkinter的特定行上將標簽和輸入框同時居中?

[英]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個標簽及其對應的輸入框,我想將每組標簽及其輸入移動到其行的中心。 我將不勝感激。

您可以從設置gridweight開始,該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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM