Tkinter Click Counter

Let’s say you want to display the number of times a button has been clicked in a Tkinter app.

This app will use a counter variable that is part of the root object.

Instead of counter, the variable will be root.counter.

This avoids problems with local and global variables getting mixed up (discussed in Python Variable Scope).

from Tkinter import *
root = Tk()

#variable is stored in the root object
root.counter = 0

def clicked():
    root.counter += 1
    L['text'] = 'Button clicked: ' + str(root.counter)
        
b = Button(root, text="Click Me", command=clicked)
b.pack()

L = Label(root, text="No clicks yet.")
L.pack()

root.mainloop()

Notes:

  • The Button object has a command attribute that matches the name of a function, clicked, defined earlier in the program.
  • The “root.counter += 1 ” command adds one to the counter variable.
  • If we used “counter = 0” and “counter += 1” instead, we would get an error because Python would interpret counter as a new local variable inside the clicked() function.
  • L is the name of a Label widget object (displays text).
  • L[‘text’] can be used to access the text of the command – the program uses that to change the label text.

Adding a bit of complexity:

Now we can have different functions connected to the same button, depending on the situation.

This program switches the click function to a multiplier after 20 clicks:

def clicked():
    root.counter += 1
    L['text'] = 'Button clicked: ' + str(root.counter)
    
    #create a new label after 20 clicks
    if root.counter > 20:
        hyper = Label(root, text="Hyper Mode!")
        hyper.pack()
        
        #change the click function after 20 clicks
        b.config(command = hyper_click)
    

def hyper_click():
    root.counter = int(1.08 * root.counter)
    L['text'] = 'Button clicked: ' + str(root.counter)


b = Button(root, text="Click Me", command=clicked)
b.pack()

L = Label(root, text="No clicks yet.")
L.pack()

Notice how the button’s config() function is used in the example:

b.config(command = hyper_click)

This changes the function that is called when the button is clicked.

Also notice that a Label widget object can be created in the middle of the program as part of the button click event.