tkinter 的入口是 Tk(),它会返回一个根窗口对象,随后通过 mainloop() 进入事件循环。
import tkinter as tk
root = tk.Tk() # 创建根窗口
root.title("示例窗口") # 设置标题
root.geometry("400x300") # 设置大小和位置
root.resizable(True, True) # 允许水平/垂直拉伸
root.mainloop() # 进入事件循环
下面列出几种最常用的控件及其基本用法。
label = tk.Label(root, text="Hello, tkinter!", font=("Arial", 14))
label.pack(pady=10) # 使用 pack 布局
def on_click():
label.config(text="按钮被点击了!")
btn = tk.Button(root, text="点我", command=on_click)
btn.pack(pady=5)
entry = tk.Entry(root, width=30)
entry.pack(pady=5)
def show_input():
print("输入内容:", entry.get())
tk.Button(root, text="打印输入", command=show_input).pack()
txt = tk.Text(root, height=5, width=40)
txt.pack(pady=5)
txt.insert(tk.END, "这里是多行文本框的默认内容。")
canvas = tk.Canvas(root, width=200, height=150, bg="white")
canvas.pack(pady=5)
canvas.create_rectangle(20,20,180,130, outline="blue", width=2)
canvas.create_text(100,75, text="Canvas 示例")
tkinter 提供三种布局方式:
# grid 示例
tk.Label(root, text="用户名:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
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, sticky="e")
tk.Entry(root, show="*").grid(row=1, column=1, padx=5, pady=5)
tk.Button(root, text="登录").grid(row=2, column=0, columnspan=2, pady=10)
通过 widget.bind(event, handler) 可以把任意 GUI 事件关联到自定义函数。
def on_key(event):
print(f"按下了键: {event.keysym}")
def on_click(event):
print(f"鼠标坐标: ({event.x}, {event.y})")
root.bind("", on_key) # 键盘事件
root.bind("", on_click) # 左键点击事件
menubar = tk.Menu(root)
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="打开", command=lambda: print("打开文件"))
file_menu.add_separator()
file_menu.add_command(label="退出", command=root.quit)
menubar.add_cascade(label="文件", menu=file_menu)
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="关于", command=lambda: tk.messagebox.showinfo("关于", "tkinter 示例"))
menubar.add_cascade(label="帮助", menu=help_menu)
root.config(menu=menubar) # 将菜单绑定到根窗口
ttk 提供更现代的外观,例如 ttk.Combobox(下拉框)和 ttk.Treeview(树形表格)。
from tkinter import ttk
# 下拉框
combo = ttk.Combobox(root, values=["选项1","选项2","选项3"])
combo.current(0)
combo.pack(pady=5)
# Treeview 示例
tree = ttk.Treeview(root, columns=("size","date"), show="headings")
tree.heading("size", text="大小")
tree.heading("date", text="日期")
tree.insert("", tk.END, values=("10KB","2025-11-20"))
tree.pack(pady=5)
root.quit() – 退出事件循环。widget.destroy() – 销毁控件。widget.focus_set() – 设置焦点,配合键盘事件使用。widget.after(ms, func) – 延时调用,常用于定时器。若想了解更完整的 API,请参考官方文档 https://docs.python.org/3/library/tkinter.html。