Hi,
I wanted to ask if somebody could help me on the following problem:

I want to check how often a button in python/tk is clicked.

I tried the folowing but it doesn't work:

click=0
      def button_clicked():
       click=click+1
       print click

but this won't work because the variable click in the function is different(local) to the
variable outside of the function.

Any suggestions?

Dani AI

Generated

ran into a scope issue: assigning to a name inside a function creates a local variable, so the outer counter wasn't changed. 's global suggestion does fix that, but globals make maintenance harder as the UI grows. Preferred, more robust patterns are shown below: attach the counter to the GUI object, use Tkinter's IntVar (keeps widget state in sync), or capture the counter in a closure (with nonlocal in Python 3 or a mutable container in older Python).

A simple class-based approach (recommended for GUIs) keeps state together:

import tkinter as tk

class ClickApp:
    def __init__(self, root):
        self.count = 0
        self.label = tk.Label(root, text="Clicked: 0")
        self.label.pack()
        btn = tk.Button(root, text="Click me", command=self.on_click)
        btn.pack()

    def on_click(self):
        self.count += 1
        self.label.config(text="Clicked: " + str(self.count))

root = tk.Tk()
app = ClickApp(root)
root.mainloop()

Alternatives:

  • Using an IntVar ties the counter to widgets directly (useful when a Label should update automatically):
import tkinter as tk

root = tk.Tk()
count_var = tk.IntVar(value=0)
tk.Label(root, textvariable=count_var).pack()

def on_click():
    count_var.set(count_var.get() + 1)

tk.Button(root, text="Click", command=on_click).pack()
root.mainloop()
  • A closure can be compact: in Python 3 use nonlocal; in Python 2 use a one-item list to hold the count.

Troubleshooting notes: pass the function object to command (use command=handler, not command=handler()), remember print() is a function in Python 3, and prefer instance state or IntVar over globals for clearer, testable code.

Recommended Answers

All 2 Replies

click=0
      def button_clicked():
       global click
       click=click+1
       print click

thanks ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.