Python Tkinter Button

介绍

Tkinter 的 Button 是用于创建按钮控件的类,点击按钮时可以触发指定的函数或事件。它是 GUI 应用中最常用的交互元素之一,支持自定义文本、图标、颜色和行为。

Button 基本用法

以下是创建简单按钮的示例,包含按钮的基本属性和点击事件绑定:

import tkinter as tk
from tkinter import messagebox

def on_button_click():
    """按钮点击时触发的函数"""
    messagebox.showinfo("提示", "按钮被点击了!")

# 创建主窗口
root = tk.Tk()
root.title("Button 示例")
root.geometry("300x200")  # 窗口大小:宽x高

# 创建按钮
button = tk.Button(
    root,                  # 父容器
    text="点击我",          # 按钮文本
    command=on_button_click  # 点击时调用的函数
)

# 显示按钮(pack() 用于布局)
button.pack(pady=50)  # pady设置上下边距

# 进入事件循环
root.mainloop()

Button 常用属性

按钮支持多种属性自定义外观和行为,以下是常用属性示例:

属性 说明 可选值示例
text 按钮文本 “点击我”
command 点击时触发的函数 on_click 或 lambda: func()
font 文本字体(名称、大小、样式) ("微软雅黑", 12, "bold")
fg 文本颜色 “red” 或 “#ff0000”
bg 背景颜色 “blue” 或 “#0000ff”
width 按钮宽度(字符数) 10
height 按钮高度(行数) 2
state 状态(正常/禁用) tk.NORMAL / tk.DISABLED
relief 边框样式 tk.RAISED / tk.SUNKEN
bd 边框宽度 3
cursor 鼠标悬停时的光标样式 “hand2”(手型)
image 按钮图标(需配合 PhotoImage 使用) tk.PhotoImage(file="icon.png")

通过组合这些属性,可以创建符合需求的交互按钮,实现丰富的用户界面功能。

例子

import tkinter as tk

def increase_count():
    """增加计数器数值"""
    global count
    count += 1
    # 更新按钮文本
    count_button.config(text=f"计数: {count}")

# 初始化计数器
count = 0

# 创建主窗口
root = tk.Tk()
root.title("Button 属性示例")
root.geometry("400x300")

# 1. 带样式的普通按钮
styled_button = tk.Button(
    root,
    text="样式按钮",
    font=("微软雅黑", 12, "bold"),  # 字体:名称、大小、加粗
    fg="white",                     # 文字颜色
    bg="#4CAF50",                   # 背景颜色
    width=15,                       # 宽度(字符数)
    height=2,                       # 高度(行数)
    relief=tk.RAISED,               # 边框样式(RAISED/SUNKEN/FLAT等)
    bd=3,                           # 边框宽度
    cursor="hand2"                  # 鼠标悬停时的光标样式
)
styled_button.pack(pady=10)

# 2. 计数按钮(动态更新文本)
count_button = tk.Button(
    root,
    text=f"计数: {count}",
    command=increase_count,
    font=("SimHei", 10),
    fg="blue",
    bg="#f0f0f0"
)
count_button.pack(pady=10)

# 3. 退出按钮
exit_button = tk.Button(
    root,
    text="退出程序",
    command=root.quit,  # 直接调用窗口的退出方法
    fg="white",
    bg="#f44336",
    width=10
)
exit_button.pack(pady=10)

root.mainloop()

绑定带参数的函数

如果需要给按钮点击事件传递参数,可以使用 lambda 表达式:

import tkinter as tk
from tkinter import messagebox

def show_message(message):
    """显示带参数的消息"""
    messagebox.showinfo("消息", message)

root = tk.Tk()
root.title("带参数的按钮")
root.geometry("300x200")

# 使用lambda传递参数
button1 = tk.Button(
    root,
    text="提示1",
    command=lambda: show_message("这是第一个提示")
)
button1.pack(pady=5)

button2 = tk.Button(
    root,
    text="提示2",
    command=lambda: show_message("这是第二个提示")
)
button2.pack(pady=5)

# 传递多个参数
button3 = tk.Button(
    root,
    text="计算结果",
    command=lambda: show_message(f"3 + 5 = {3+5}")
)
button3.pack(pady=5)

root.mainloop()

按钮状态控制

按钮可以通过 state 属性设置状态(正常/禁用),常用于动态控制交互:

import tkinter as tk

def toggle_button_state():
    """切换按钮状态"""
    current_state = target_button["state"]
    if current_state == tk.NORMAL:
        target_button.config(state=tk.DISABLED, text="已禁用")
        toggle_btn.config(text="启用按钮")
    else:
        target_button.config(state=tk.NORMAL, text="可点击")
        toggle_btn.config(text="禁用按钮")

root = tk.Tk()
root.title("按钮状态控制")
root.geometry("300x150")

# 目标按钮(可被控制)
target_button = tk.Button(
    root,
    text="可点击",
    state=tk.NORMAL  # 初始状态:正常(可点击)
)
target_button.pack(pady=20)

# 控制按钮
toggle_btn = tk.Button(
    root,
    text="禁用按钮",
    command=toggle_button_state
)
toggle_btn.pack()

root.mainloop()

原文出处:/show_1GWn2HunCxU.html