Tkinter支持三种几何管理器:网格管理器,包管理器,位置管理器
提示:由于每个管理器都有自己放置小构件的风格,最好不要在同一个容器中的小构件使用多个管理器。可以使用框架作为子容器以获取期望的布局。
1.网格管理器
#几何管理器(1)-----网格管理器 ''' 网格管理器将小构件,放在一个不可见网格的每个单元内。可以将小构件放在某个特定的行和列内,也可以使 用rowspan和columnspan参数将小构件放在多行和多列中。 ''' from tkinter import * class GridManagerDemo: window = Tk() window.title("Grid Manager Demo") message = Message(window, text = "This Message widget occupies three rows and two columns") message.grid(row = 1, column = 1, rowspan = 3, columnspan = 2) Label(window, text = "First Name:").grid(row = 1, column = 3) Entry(window).grid(row = 1, column = 4, padx = 5, pady = 5) Label(window, text = "Last Name:").grid(row = 2, column = 3) Entry(window).grid(row = 2, column = 4) Button(window, text = "Get Name").grid(row = 3, padx = 5, pady = 5,column = 4, sticky = E) window.mainloop() GridManagerDemo()
2.包管理器
#几何管理器(2)-----包管理器 ''' 包含管理器将小构件依次的一个放置在另一个的顶部或将他们一个挨着一个的放置。 ''' #第一种 from tkinter import * class PackManagerDemo: def __init__(self): window = Tk() window.title("Pack Mananger Demo 1") Label(window, text = "Blue", bg="blue").pack() # fill通过X,Y,BOTH 来填充水平,垂直,或者两个方向的空间 #expand告诉管理器分配额外的空间给小构件 Label(window, text = "Red", bg = "red").pack(fill = BOTH, expand = 1) Label(window, text = "Green", bg = "green").pack(fill = BOTH) window.mainloop() PackManagerDemo() #第二种 class PackManagerDemoWithSide: window = Tk() window.title("Pack Manager Demo 2") #side可以是LEFT, RIGHT, TOP, BOTTOM,默认是TOP。 Label(window, text = "Blue", bg="blue").pack(side = LEFT) Label(window, text = "Red", bg = "red").pack(side = LEFT, fill = BOTH, expand = 1) Label(window, text = "Green", bg = "green").pack(side = LEFT, fill = BOTH) window.mainloop() PackManagerDemoWithSide()
3.位置管理器
#几何管理器(3)-----位置管理器 ''' 位置管理器将小构件放在绝对位置上。 ''' from tkinter import * class PlaceManagerDemo: def __init__(self): window = Tk() window.title("Place Manager Demo") Label(window, text = "Blue", bg = "blue").place(x = 20, y = 20) Label(window, text = "Red", bg = "red").place(x = 50, y = 50) Label(window, text = "Green", bg = "green").place(x = 80, y = 80) window.mainloop() PlaceManagerDemo()