Python中的按钮点击计数器

时间:2019-07-05 13:45:13

标签: 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()

我知道event.x用于捕获鼠标的位置。因此,程序的结果与预期的不同。我想要别的东西。您能帮我解决问题吗?

3 个答案:

答案 0 :(得分:3)

您不需要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!!!')

编辑:因为您不需要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()

答案 1 :(得分:0)

您可以使用如下装饰器将“计数器”添加为属性:

event.originalEvent.dataTransfer

答案 2 :(得分:0)

我不知道这是不是最好的方法,但是这段代码有效

import tkinter as tk

class Main():

    def __init__(self, root):
        self.root = root
        self.count = 0

        frame = tk.Frame(self.root)
        frame.pack()

        btn = tk.Button(frame, text ='click me')
        btn.pack()
        btn.bind('<Button-1>', self.click)

        self.lbl = tk.Label(frame, text = 'Count is 0')
        self.lbl.pack()

    def click(self, event):
        self.count += 1
        self.lbl.config(text=f'count {self.count}')


if __name__=="__main__":
    root = tk.Tk()
    Main(root)
    root.mainloop()
相关问题