居中对齐框架中的一组小部件

Center align a group of widgets in a frame

如果框架的行中只有一个小部件,我可以使用 sticky= 将其对齐到任何一侧,或者通过省略 sticky.

居中对齐

但是,当一行中有多个列时,其中的对象最终会左对齐:

虽然我希望他们留在中心(同时保持大小)。

代码摘录:

from Tkinter import N,W,S,E,Tk
import ttk
import Tkinter as tkinter

root = Tk()
mainframe = ttk.Frame(root)
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

tv_town_fr = ttk.Frame(mainframe)
tv_town_fr.grid(row=3, sticky=(W,E))

tv_town_add = ttk.Button(tv_town_fr,text="+",width=4)
tv_town_add.grid(row=1,column=1)
tv_town_edit = ttk.Button(tv_town_fr,text="*",width=4)
tv_town_edit.grid(row=1,column=2)
tv_town_del = ttk.Button(tv_town_fr,text="-",width=4)
tv_town_del.grid(row=1,column=3)
tv_town_up = ttk.Button(tv_town_fr,text=u"↑",width=4)
tv_town_up.grid(row=1,column=4)
tv_town_down = ttk.Button(tv_town_fr,text=u"↓",width=4)
tv_town_down.grid(row=1,column=5)

tv_query_fr = ttk.Frame(mainframe)
tv_query_fr.grid(row=6, sticky=(W,E))

tv_query_add = ttk.Button(tv_query_fr,text="+",width=5)
tv_query_add.grid(row=1,column=1)
tv_query_edit = ttk.Button(tv_query_fr,text="*",width=5)
tv_query_edit.grid(row=1,column=2)
tv_query_del = ttk.Button(tv_query_fr,text="-",width=5)
tv_query_del.grid(row=1,column=3)
tv_query_up = ttk.Button(tv_query_fr,text=u"↑",width=5)
tv_query_up.grid(row=1,column=4)
tv_query_down = ttk.Button(tv_query_fr,text=u"↓",width=5)
tv_query_down.grid(row=1,column=5)

使用 grid 时水平居中一组小部件的最简单解决方案是在所有可见项目的左侧和右侧创建一个空列,然后为这些列赋予权重,以便所有额外的 space 都分配给空列。

例子

import Tkinter as tk

root = tk.Tk()
root.geometry("400x200")

label = tk.Label(root, text="Hello, world")
buttons = tk.Frame(root)
label.pack(side="top", fill="both", expand=True)
buttons.pack(side="bottom", fill="x")

b1 = tk.Button(buttons, text="one")
b2 = tk.Button(buttons, text="two")
b3 = tk.Button(buttons, text="three")

b1.grid(row=0, column=1)
b2.grid(row=0, column=2)
b3.grid(row=0, column=3)

# give empty columns a weight so that the consume
# all extra space
buttons.grid_columnconfigure(0, weight=1)
buttons.grid_columnconfigure(4, weight=1)

root.mainloop()