Featured image of post Python Basic 21 Tkinter grid 布局

Python Basic 21 Tkinter grid 布局

本篇文章主要 Python Tkinter 的 grid 布局

Grid布局是Tkinter中最常用的几何管理器之一,它使用行列网格来组织小部件,非常适合创建表格状的界面布局~

Grid布局基本用法

1
widget.grid(options...)

基本参数速查表 🏷️

参数 说明 示例
row 行号 (从0开始) row=0
column 列号 (从0开始) column=1
rowspan 跨行数 rowspan=2
columnspan 跨列数 columnspan=3
padx/pady 外间距(x/y方向) padx=5, pady=10
ipadx/ipady 内间距(x/y方向) ipadx=2, ipady=3
sticky 对齐方式(NSEW) sticky="nsew"

🌟 示例代码 (๑•̀ㅂ•́)و✧

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import tkinter as tk

root = tk.Tk()
root.title("Grid演示 (~˘▾˘)~")

# 第一行
tk.Label(root, text="用户名:").grid(row=0, column=0, padx=5, pady=5)
tk.Entry(root).grid(row=0, column=1, padx=5, pady=5)

# 第二行
tk.Label(root, text="密码:").grid(row=1, column=0, padx=5, pady=5)
tk.Entry(root, show="*").grid(row=1, column=1, padx=5, pady=5)

# 第三行跨两列
tk.Button(root, text="登录", width=15).grid(row=2, column=0, columnspan=2, pady=10)

root.mainloop()

📌 重要特性说明

sticky参数详解 (๑•̀ω•́)ノ

  • N - 顶部对齐
  • S - 底部对齐
  • E - 右对齐
  • W - 左对齐
  • 可以组合使用:"nsew"表示撑满整个单元格
1
2
# 让按钮充满整个单元格
tk.Button(root, text="撑满").grid(sticky="nsew")

行列权重配置 ⚖️

1
2
3
4
5
6
# 使第1列和第2列能自动扩展
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

# 使第1行能自动扩展
root.grid_rowconfigure(0, weight=1)

空白单元格处理 🧩

默认情况下,空的grid单元格不会显示,但会影响布局。可以使用grid_remove()临时隐藏部件。

🎯 实用小技巧

  1. 快速调试边界 🔍: 给每个部件加边框borderwidth=1, relief="solid"

  2. 单元格合并 🧩: 使用columnspanrowspan跨越多行多列

  3. 让界面自适应 📱: 结合weight设置和sticky="nsew"

  4. 默认空白留边 🏡: 使用padxpady让界面不显得拥挤

🚀 进阶用法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 创建一个简单的计算器界面布局
buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', 'C', '=', '+'
]

for i in range(4):
    root.grid_rowconfigure(i, weight=1)
    root.grid_columnconfigure(i, weight=1)

for i, text in enumerate(buttons):
    row = i // 4
    col = i % 4
    btn = tk.Button(root, text=text, padx=20, pady=20)
    btn.grid(row=row, column=col, sticky="nsew")

Grid布局是Tkinter中最灵活的布局方式之一,掌握它能让你轻松创建各种整齐有序的GUI界面!٩(◕‿◕。)۶

Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计