Button 按钮与 command

51.4 Button 按钮与 command

Button 的 command=回调函数,点击时无参数调用。

lambda 可传参:command=lambda: func(123)。

计数器按钮

# ========================================
# 示例:按钮点击计数
# 说明:nonlocal 修改外层函数变量
# ========================================
import tkinter as tk

root = tk.Tk()
count = tk.IntVar(value=0)  # 整数变量

label = tk.Label(root, textvariable=count, font=('', 20))
label.pack(pady=10)

def add_one():
    count.set(count.get() + 1)  # 每次点击 +1

tk.Button(root, text='+1', width=10, command=add_one).pack()
root.mainloop()