Python中的按钮点击计数器

Man*_*dia 0 python tkinter

我正在尝试编写一个 Python 程序来计算单击按钮的次数。我编写了以下代码:

import tkinter
from tkinter import ttk


def clicked(event):
    event.x = event.x + 1
    label1.configure(text=f'Button was clicked {event.x} times!!!')


windows = tkinter.Tk()
windows.title("My Application")
label = tkinter.Label(windows, text="Hello World")
label.grid(column=0, row=0)
label1 = tkinter.Label(windows)
label1.grid(column=0, row=1)
custom_button = tkinter.ttk.Button(windows, text="Click on me")

custom_button.bind("<Button-1>", clicked)
custom_button.grid(column=1, row=0)
windows.mainloop()
Run Code Online (Sandbox Code Playgroud)

我知道 event.x 用于捕获鼠标的位置。因此程序的结果并不如预期。我想要别的东西。你能帮我解决这个问题吗。

fur*_*ras 6

你不需要event这个。你需要自己的变量来计算它。

并且它必须是全局变量,因此它将在函数之外保留值。

count = 0

def clicked(event):
    global count # inform funtion to use external variable `count`

    count = count + 1

    label1.configure(text=f'Button was clicked {count} times!!!')
Run Code Online (Sandbox Code Playgroud)

编辑:因为你不需要event所以你也可以使用command=代替bind

import tkinter as tk
from tkinter import ttk


count = 0

def clicked(): # without event because I use `command=` instead of `bind`
    global count

    count = count + 1

    label1.configure(text=f'Button was clicked {count} times!!!')


windows = tk.Tk()
windows.title("My Application")

label = tk.Label(windows, text="Hello World")
label.grid(column=0, row=0)

label1 = tk.Label(windows)
label1.grid(column=0, row=1)

custom_button = ttk.Button(windows, text="Click on me", command=clicked)
custom_button.grid(column=1, row=0)

windows.mainloop()
Run Code Online (Sandbox Code Playgroud)