






























几何管理器
控制控件的大小和位置
| 管理器 | 最佳适用场景 | 模型 |
|---|---|---|
pack |
简单的线性布局 | 从上/下/左/右堆叠 |
grid |
表单、表格 | 行/列网格 |
place |
绝对定位 | x/y 坐标或相对位置 |
⚠️ 不要在同一容器中混用管理器
不要对共享同一个父容器的控件同时使用 pack 和 grid——这会导致无限几何循环并造成程序冻结。
pack()widget.pack(side=TOP, fill=NONE, expand=False, anchor=CENTER, padx=0, pady=0)
| 选项 | 取值 | 说明 |
|---|---|---|
side |
TOP, BOTTOM, LEFT, RIGHT |
沿着哪一侧堆叠 |
fill |
NONE, X, Y, BOTH |
是否填充分配的空间 |
expand |
True / False |
窗口变大时是否占据额外空间 |
anchor |
N, S, E, W, NE, NW, SE, SW, CENTER |
有多余空间时的对齐方式 |
padx / pady |
int 或 (int, int) |
外部边距(像素) |
sidebar_layout.py
container = ttk.Frame(root)
container.pack(fill=tk.BOTH, expand=True)
sidebar = ttk.Frame(container, width=120)
sidebar.pack(side=tk.LEFT, fill=tk.Y)
content = ttk.Frame(container)
content.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
grid()widget.grid(row=0, column=0, rowspan=1, columnspan=1, sticky="", padx=0, pady=0)
💡 columnconfigure / rowconfigure
当窗口调整大小时,始终对需要拉伸的列调用 parent.columnconfigure(n, weight=1)。
grid_form.py
root.columnconfigure(1, weight=1)
ttk.Label(root, text="用户名:").grid(row=0, column=0, sticky="e", padx=8, pady=6)
ttk.Entry(root).grid (row=0, column=1, sticky="ew", padx=8)
ttk.Label(root, text="密码:").grid(row=1, column=0, sticky="e", padx=8, pady=6)
ttk.Entry(root, show="*").grid (row=1, column=1, sticky="ew", padx=8)
ttk.Button(root, text="登录").grid(row=2, column=0, columnspan=2, pady=12)
place()widget.place(x=0, y=0, relx=0.0, rely=0.0, width=None, relwidth=None, anchor=NW)
place_center.py
# 使用相对坐标将控件居中
label.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
app_skeleton.py
toolbar = ttk.Frame(root, relief="raised")
toolbar.pack(side="top", fill="x")
content = ttk.Frame(root)
content.pack(fill="both", expand=True)
statusbar = ttk.Label(root, text="就绪", relief="sunken")
statusbar.pack(side="bottom", fill="x")
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。