Use grid_propagate(0)
or pack_propagate(0)
,取决于所使用的几何管理器。0
只是False
,这告诉 tkinter 关闭几何传播。
默认情况下,传播处于开启状态,容器会增大/缩小到足以容纳其内容。
我假设您想要的布局是这样的:
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
root = tk.Tk()
MainFrame = tk.Frame(root, width=385, height=460, relief='raised', borderwidth=5)
LabelFrame = tk.Frame(MainFrame, width=375, height=115, relief='raised', borderwidth=5)
ButtonFrame = tk.Frame(MainFrame, width=375, height=330, relief='raised', borderwidth=5)
some_label = tk.Label(LabelFrame, text='Simple Text')
some_button = tk.Button(ButtonFrame, text='Quit', command=root.destroy)
for frame in [MainFrame, LabelFrame, ButtonFrame]:
frame.pack(expand=True, fill='both')
frame.pack_propagate(0)
for widget in [some_label, some_button]:
widget.pack(expand=True, fill='x', anchor='s')
root.mainloop()
与grid管理器的区别仅在循环部分(注意sticky
and row/column configure
):
...
for frame in [MainFrame, LabelFrame, ButtonFrame]:
# sticky='nswe' acts like fill='both'
frame.grid(sticky='nswe')
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
frame.grid_propagate(0)
for widget in [some_label, some_button]:
# sticky='wse' acts like fill='x' + anchor='s'
widget.grid(sticky='wse')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
...