如果您希望其他人帮助您,您真的需要提供一个最小的工作演示!
在我看来,使用 Tkinter 网格设计器时更容易处理居中元素(请参阅何时使用哪个布局管理器)。您只需将元素放在矩阵上即可。网格布局的主要缺点是难以调整元素的大小(没有填充选项)。我们必须将权重放在行和列上(请参阅grid_rowconfigure
和grid_columnconfigure
)并将控件粘贴在每个边缘(NSWE)上。
在浏览代码之前,警告:不要在同一个根框架中混合网格和打包!在我的示例中,我使用 pack 来堆叠选项卡,并使用 grid 来管理选项卡本身内的元素。我已将此库用于 Notebook 类。
root = Tk()
#notebook
nb = notebook(root )
# Admin Tab
admin = Frame( nb() , name='admin')
admin.grid( sticky=N+S+W+E)
# Every row and column have a wieght of one when resizing (linear transformation)
admin.grid_rowconfigure(0, weight=1)
admin.grid_rowconfigure(1, weight=1)
admin.grid_rowconfigure(2, weight=1)
admin.grid_columnconfigure(1, weight=1)
admin.grid_columnconfigure(2, weight=1)
admin.grid_columnconfigure(3, weight=1)
new_customer = Frame( admin , relief = RIDGE )
# Labels init
Label(admin, text="Name").grid(row=0, column = 0, sticky=N+S+W+E)
Label(admin, text="Type").grid(row=1, column = 0, sticky=N+S+W+E)
Label(admin, text="Date").grid(row=1, column = 2, sticky=N+S+W+E)
# Elements Init
first_name = Entry(admin)
middle_name = Entry(admin)
family_name = Entry(admin)
date = Entry(admin)
type_box = OptionMenu( admin , "one", "two", "three")
reset_button = Button( admin, text = "Reset Value" )
submit_button = Button( admin, text = "Submit" )
# Place elements
first_name. grid(row=0 , column =1, sticky=N+S+W+E)
middle_name. grid(row=0 , column =2, sticky=N+S+W+E)
family_name. grid(row=0 , column =3, sticky=N+S+W+E)
date. grid(row =1 , column =3, sticky=N+S+W+E)
type_box. grid(row =1 , column =1, sticky=N+S+W+E)
reset_button. grid(row =2 , column = 1 ,sticky=N+S+W+E)
submit_button. grid(row =2 , column = 3 , sticky=N+S+W+E)
# Add Tabls
nb.add_screen( admin , "Admin" )
nb.add_screen( Frame(nb()) , "Others" )
if __name__ == "__main__":
root.mainloop()
该应用程序并不完美(没有填充,行没有扩展),但它应该给你一个良好的开端。