Tkinter - 几何管理器

几何管理器
控制控件的大小和位置

管理器 最佳适用场景 模型
pack 简单的线性布局 从上/下/左/右堆叠
grid 表单、表格 行/列网格
place 绝对定位 x/y 坐标或相对位置

⚠️ 不要在同一容器中混用管理器

不要对共享同一个父容器的控件同时使用 packgrid——这会导致无限几何循环并造成程序冻结。


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")
posted @ 2026-07-10 08:59  箫笛  阅读(9)  评论(0)    收藏  举报