1. Button 基础
1.1 创建最简单的按钮
import tkinter as tk
# 创建主窗口
root = tk.Tk()
root.title("Button 教程")
# 创建按钮
button = tk.Button(root, text="点击我")
button.pack(pady=10) # 将按钮添加到窗口并设置垂直间距
root.mainloop()
效果:窗口中显示一个文本为“点击我”的按钮,但点击无响应(未绑定事件)。
2. 配置 Button 属性
2.1 常用参数
参数名 | 作用 | 示例值 |
text | 按钮显示的文本 | text="提交" |
command | 点击按钮时触发的函数 | command=callback_function |
bg / fg | 背景色 / 前景色(文本颜色) | bg="blue", fg="white" |
font | 设置字体和大小 | font=("Arial", 12) |
width / height | 按钮的宽度和高度(字符单位) | width=10, height=2 |
state | 按钮状态(正常/禁用) | state="disabled" |
2.2 示例:自定义按钮样式
def say_hello():
print("Hello Tkinter!")
button = tk.Button(
root,
text="打招呼",
command=say_hello,
bg="lightgreen",
fg="black",
font=("宋体", 14, "bold"),
width=15,
height=2
)
button.pack(pady=20)
3. 事件处理
3.1 绑定点击事件
使用 command
参数直接绑定函数:
def button_click():
print("按钮被点击了!")
button = tk.Button(root, text="点击", command=button_click)
button.pack()
3.2 绑定其他事件(如鼠标悬停)
使用 bind
方法绑定任意事件:
def on_enter(event):
button.config(bg="yellow") # 鼠标悬停时变黄
def on_leave(event):
button.config(bg="lightgray") # 鼠标离开恢复颜色
button = tk.Button(root, text="悬停效果", bg="lightgray")
button.pack()
# 绑定事件
button.bind("<Enter>", on_enter) # 鼠标进入
button.bind("<Leave>", on_leave) # 鼠标离开
4. 布局管理
4.1 使用 pack()
button.pack(side="left", padx=5, pady=5) # 靠左对齐,设置边距
4.2 使用 grid()
button.grid(row=0, column=0, sticky="ew") # 放在第0行第0列,横向拉伸
4.3 使用 place()
button.place(x=100, y=50) # 绝对坐标定位
5. 进阶功能
5.1 禁用/启用按钮
button.config(state="disabled") # 禁用按钮
button.config(state="normal") # 启用按钮
5.2 动态修改按钮属性
def toggle_color():
current_bg = button.cget("bg") # 获取当前背景色
new_bg = "red" if current_bg == "blue" else "blue"
button.config(bg=new_bg)
button = tk.Button(root, text="切换颜色", bg="blue", command=toggle_color)
button.pack()
5.3 带图标的按钮
from tkinter import ttk
# 使用 ttk 的样式系统(需先导入 ttk)
photo = tk.PhotoImage(file="icon.png") # 加载图片
button = ttk.Button(root, image=photo, text="图标按钮", compound="left")
button.pack()
6. 注意事项
- 主循环必需:必须调用
root.mainloop()
才能显示窗口。
- 函数绑定:
command
参数传递函数名时不要加括号(例如 command=my_function
)。
- 布局冲突:避免在同一个父容器中混用
pack()
和 grid()
。
- ttk 按钮:若使用
ttk.Button
(来自 tkinter.ttk
),部分样式参数可能不同(如 bg
改为 style
)。
7. 完整示例
import tkinter as tk
from tkinter import ttk
def submit():
print(f"用户名: {entry.get()}")
button_submit.config(state="disabled") # 提交后禁用按钮
root = tk.Tk()
root.title("登录界面")
# 输入框
entry = tk.Entry(root, width=20)
entry.pack(pady=10)
# 提交按钮
button_submit = ttk.Button(
root,
text="提交",
command=submit
)
button_submit.pack(pady=5)
# 取消按钮
button_cancel = ttk.Button(
root,
text="取消",
command=root.destroy # 关闭窗口
)
button_cancel.pack(pady=5)
root.mainloop()