Tkinter快速上手【快速入门】
以下是 Tkinter 快速上手指南,包含基础用法、核心组件和实用示例,帮助你快速构建简单的 GUI 应用。
1. 基础框架
最小 Tkinter 程序
import tkinter as tk
# 创建主窗口
root = tk.Tk()
root.title("我的第一个 GUI") # 窗口标题
root.geometry("300x200") # 窗口大小 (宽x高)
# 添加一个标签
label = tk.Label(root, text="Hello Tkinter!")
label.pack() # 将组件放置到窗口中
# 启动主循环
root.mainloop()
效果:
一个带文字标签的空白窗口。
2. 核心组件
(1) 按钮 (Button
)
def button_click():
print("按钮被点击了!")
button = tk.Button(root, text="点击我", command=button_click)
button.pack()
(2) 输入框 (Entry
)
entry = tk.Entry(root)
entry.pack()
def get_text():
print("输入的内容:", entry.get())
tk.Button(root, text="获取输入", command=get_text).pack()
(3) 文本框 (Text
)
text = tk.Text(root, height=5, width=30)
text.pack()
def get_text_content():
print(text.get("1.0", tk.END)) # 从第1行第0列获取到末尾
tk.Button(root, text="读取文本框", command=get_text_content).pack()
(4) 单选按钮 (Radiobutton
)
radio_var = tk.StringVar(value="A") # 默认选中A
tk.Radiobutton(root, text="选项A", variable=radio_var, value="A").pack()
tk.Radiobutton(root, text="选项B", variable=radio_var, value="B").pack()
def show_choice():
print("当前选中:", radio_var.get())
tk.Button(root, text="显示选择", command=show_choice).pack()
(5) 复选框 (Checkbutton
)
check_var = tk.BooleanVar() # 布尔类型变量
tk.Checkbutton(root, text="同意协议", variable=check_var).pack()
def check_state():
print("是否选中:", check_var.get())
tk.Button(root, text="检查状态", command=check_state).pack()
(6) 下拉菜单 (OptionMenu
)
options = ["Python", "Java", "C++"]
option_var = tk.StringVar(value=options[0])
tk.OptionMenu(root, option_var, *options).pack()
def show_selected():
print("选择了:", option_var.get())
tk.Button(root, text="显示选择", command=show_selected).pack()
3. 布局管理
(1) pack()
- 简单堆叠
tk.Label(root, text="顶部").pack(side="top")
tk.Label(root, text="底部").pack(side="bottom")
tk.Label(root, text="左边").pack(side="left")
tk.Label(root, text="右边").pack(side="right")
(2) grid()
- 网格布局
tk.Label(root, text="第0行第0列").grid(row=0, column=0)
tk.Label(root, text="第1行第1列").grid(row=1, column=1)
tk.Entry(root).grid(row=0, column=1) # 输入框放在第0行第1列
(3) place()
- 绝对定位
tk.Label(root, text="坐标 (100,50)").place(x=100, y=50)
4. 综合示例:图片查看器
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
def open_image():
file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg *.png")])
if file_path:
img = Image.open(file_path)
img.thumbnail((300, 300))
photo = ImageTk.PhotoImage(img)
label.config(image=photo)
label.image = photo # 防止图片被垃圾回收
root = tk.Tk()
root.title("图片查看器")
tk.Button(root, text="打开图片", command=open_image).pack()
label = tk.Label(root)
label.pack()
root.mainloop()
功能:
点击按钮选择图片,并在窗口中显示缩略图。
5. 常见问题
(1) 如何关闭窗口?
root.destroy() # 销毁窗口
(2) 如何设置窗口图标?
root.iconbitmap("icon.ico") # 支持 .ico 文件
(3) 如何弹出消息框?
from tkinter import messagebox
messagebox.showinfo("标题", "这是一个提示!")
6. 学习资源
- 官方文档:Tkinter Docs
- 书籍推荐:《Python GUI Programming with Tkinter》
通过以上内容,你可以快速上手 Tkinter,构建简单的桌面应用。如果需要更复杂的功能(如表格、多线程),可以进一步学习 ttk
模块或结合其他库(如 matplotlib
嵌入图表)。