# 图形界面开发 Python 有多个 GUI 库:Tkinter(内置/跨平台)、PyQt5/PySide6(功能强大)、wxPython(原生外观)。本节介绍 Tkinter。 ## 第一个窗口 ```python import tkinter as tk root = tk.Tk() root.title("我的窗口") root.geometry("400x300") label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 24)) label.pack(pady=50) root.mainloop() ``` ## 常用控件 ```python import tkinter as tk from tkinter import messagebox def on_click(): messagebox.showinfo("提示", f"你输入了:{entry.get()}") root = tk.Tk() root.title("控件演示") # 标签 tk.Label(root, text="用户名:").grid(row=0, column=0, padx=5, pady=5) # 输入框 entry = tk.Entry(root, width=20) entry.grid(row=0, column=1, padx=5, pady=5) # 按钮 tk.Button(root, text="确定", command=on_click).grid(row=1, column=0, columnspan=2, pady=10) root.mainloop() ``` ## 常用控件一览 | 控件 | 用途 | 关键参数 | |------|------|---------| | `Label` | 文本/图片显示 | `text`, `image`, `font` | | `Button` | 按钮 | `text`, `command`, `state` | | `Entry` | 单行输入 | `textvariable`, `show` | | `Text` | 多行文本 | `height`, `width` | | `Listbox` | 列表选择 | `listvariable` | | `Checkbutton` | 复选框 | `variable`, `onvalue`, `offvalue` | | `Radiobutton` | 单选按钮 | `variable`, `value` | | `Canvas` | 画布/绑定绘图 | `width`, `height` | | `Menu` | 菜单栏 | - | ## 布局管理 ```python # pack - 依次排列 widget.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5) # grid - 网格布局 widget.grid(row=0, column=1, rowspan=2, sticky=tk.W) # place - 绝对/相对定位 widget.place(x=100, y=50, relx=0.5, rely=0.5) ``` ## 总结 - Tkinter 是 Python 内置 GUI 库,无需额外安装 - 控件通过 `pack/grid/place` 布局管理器排布 - `command` 绑定回调函数处理用户交互 - `Canvas` 可用于绑定图形和自定义绘图