Python GUI入门
学习tkinter · 难度:进阶 · +15XP
Python GUI 入门 Tkinter
Tkinter 是 Python 的标准 GUI(图形用户界面)库,它基于 Tk GUI 工具包。Tkinter 随 Python 一起安装,无需额外安装任何第三方库,即可创建跨平台的桌面应用程序。虽然外观不如现代框架华丽,但 Tkinter 简单易学,非常适合快速原型开发和小型桌面工具。
创建第一个窗口
import tkinter as tk
# 创建主窗口
root = tk.Tk()
root.title('我的第一个 GUI 程序')
root.geometry('400x300') # 宽 x 高
# 添加标签
label = tk.Label(root, text='欢迎使用 Tkinter!', font=('Arial', 16))
label.pack(pady=20)
# 添加按钮
def on_click():
label.config(text='按钮被点击了!')
button = tk.Button(root, text='点击我', command=on_click, bg='blue', fg='white')
button.pack(pady=10)
# 进入主事件循环
root.mainloop()
常用控件
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title('常用控件演示')
root.geometry('400x400')
# 文本框 Entry
entry = tk.Entry(root, width=30)
entry.pack(pady=5)
# 多行文本框 Text
text = tk.Text(root, height=5, width=40)
text.pack(pady=5)
# 复选框 Checkbutton
var_check = tk.BooleanVar()
check = tk.Checkbutton(root, text='同意用户协议', variable=var_check)
check.pack(pady=5)
# 单选按钮 Radiobutton
var_radio = tk.StringVar(value='Python')
tk.Radiobutton(root, text='Python', variable=var_radio, value='Python').pack()
tk.Radiobutton(root, text='Java', variable=var_radio, value='Java').pack()
# 消息框
def show_message():
messagebox.showinfo('提示', f'你输入了: {entry.get()}')
tk.Button(root, text='显示消息', command=show_message).pack(pady=10)
root.mainloop()
布局管理器
import tkinter as tk
root = tk.Tk()
root.title('布局管理器')
# pack 布局 - 按顺序排列
tk.Label(root, text='顶部', bg='red').pack(fill='x')
tk.Label(root, text='中间', bg='green').pack(fill='both', expand=True)
tk.Label(root, text='底部', bg='blue').pack(fill='x')
# grid 布局 - 表格排列
# tk.Label(root, text='姓名').grid(row=0, column=0)
# tk.Entry(root).grid(row=0, column=1)
# place 布局 - 绝对定位
# tk.Label(root, text='固定位置').place(x=50, y=100)
root.mainloop()
Tkinter 常用控件速查
| 控件 | 说明 |
|---|---|
| Label | 显示文本或图片 |
| Button | 可点击的按钮 |
| Entry | 单行文本输入框 |
| Text | 多行文本编辑区 |
| Checkbutton | 复选框 |
| Radiobutton | 单选按钮 |
| Listbox | 列表选择框 |
| Scale | 滑块控件 |
| Menu | 菜单栏 |