0

I am trying to write a Python program to count how many times a button is clicked. I have written the following code:

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()

I know that event.x is used to capture the location of mouse. And hence the result of the program is not as expected. I want something else. Can you please help me solve the issue.

4 Answers 4

9

You don't need event for this. You need own variable to count it.

And it has to be global variable so it will keep value outside function.

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!!!')

EDIT: Because you don't need event so you can also use command= instead of 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()
Sign up to request clarification or add additional context in comments.

2 Comments

Have to check it. The event instance is unused. Will it give warning?
if you use bind then function need variable event but if you use command= then it doesn't need event. If you want to use function with both then you can use event=None - def clicked(event=None) - and bind will run with event and command will run with None
1

I don't know is this best way or not, but this code is worked

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()

1 Comment

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.
0

You can add 'counter' as an attribute with a decorator like this:

def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate


@static_vars(counter=0)
def clicked(event):
    clicked.counter += 1

Comments

0

You can add a counter to the widget and use that in your event function. This should work for buttons, entries, etc. This allows the user to reuse the event function.

Useful for when you want to change appearances of entry boxes (e.g. showing example of an entry which disappears on first focus but not second)

import tkinter
from tkinter import ttk

def clicked(event):
    event.widget.count = event.widget.count + 1
    label1.configure(text=f'This button was clicked {event.widget.count} 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.count =0
custom_button.bind("<Button-1>", clicked)
custom_button.grid(column=1, row=0)

custom2_button = tkinter.ttk.Button(windows, text="Click on me")
custom2_button.count = 0
custom2_button.bind("<Button-1>", clicked)
custom2_button.grid(column=1, row=0)

windows.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.