簡體   English   中英

在網格 Tkinter 窗口中對齊小部件

[英]Aligning widgets in a grid Tkinter window

我想在 Tkinter 創建的窗口中居中對齊我的所有小部件。 我所有的小部件都使用網格幾何系統。 我已經嘗試過列權重和行權重,但它們不適用於我沒有明確設置的行和列。 我還嘗試將整個窗口包裝在一個框架中並使用 grid(sticky=NSEW) 但它沒有任何區別。 對於我的用例,我有超過 50 行/列,我不想對它們中的每一個運行權重設置。 這是我到目前為止所擁有的:

root = Tk()
root.minsize(500, 100)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.rowconfigure(2, weight=1)
root.columnconfigure(2, weight=1)
root.title('123')
root.iconbitmap(get_res_path('icon.ico'))

status_bar = LabelFrame(root, bd=1, relief=SUNKEN)
status_bar.grid(row=1, column=0, sticky=EW)
status_bar.rowconfigure(1, weight=1)
status_bar.columnconfigure(1, weight=1)
testing_text = Label(status_bar, text='', anchor=W)
testing_text.grid(row=0, column=0, sticky=W)
status_text = Label(status_bar, text='Initializing', anchor=E)
status_text.grid(row=0, column=1, sticky=E)

ver_msg = Label(root, text='123')
ver_msg.grid(row=0, column=0)
Frame(root).pack()

在此處輸入圖像描述

我希望窗口中的每個元素(文本、輸入框和按鈕)都位於窗口的中間,如果我將窗口拖得更大,它能夠自行調整以保持在中間。

我見過很多問題,但沒有一個給我一個有效的答案。

我能想到的將整個應用程序居中的最簡單方法是將整個小部件放在一個框架內,然后在主框架上使用pack() ,例如:

frame = Frame(root)
frame.pack()

Button(frame, text='This is a button').grid(row=0,column=0)
Label(frame, text='This is a label').grid(row=1,column=0)

您可以這樣做以將您的小部件與框架的左側對齊

frame = Frame(root)
frame.pack(fill=X, padx=5)
Button(frame, text='This is a button').grid(row=0,column=0)
Label(frame, text='This is a label').grid(row=1,column=0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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