Reputation: 55
I have a button that is bound to an event function and I want that function to count the number of times the button has been clicked. So I have a variable (clicks), and i want the event function to take clicks as a parameter and increment it by one. Here is my code:
#imports
import tkinter
#variables
clicks = 0
#event functions
def click(event,clicks):
clicks += 1
print(clicks)
return clicks
#create gui
window = tkinter.Tk()
button = tkinter.Button(text = "click me!")
button.pack()
clicks = button.bind("<Button-1>",click)
#run gui
window.mainloop()
When I run the program and click the button, I get a "click() missing 1 required positional argument: 'clicks'" error. But as far as I can tell I have clicks initialized, and click takes and returns clicks, so where have I gone wrong?
Upvotes: 0
Views: 380
Reputation: 123473
There's a number of things wrong with your code. but to answer your question, it's because you didn't declare the integer clicks
variable global
in event handler function. However that alone wouldn't make everything work, so I'm going to concentrate on the other issues present (as well as fix that one).
For one, you have two objects named clicks
. As I already said, in order to change the value of the integer clicks
object, it must be declared global
in the click()
event handler function — while it is possible to pass extra arguments to event handler functions, that wouldn't help here because integers are passed by value in Python, so incrementing it there wouldn't change the value of the global variable (so I'm not going to show you how to pass extra arguments since it wouldn't be helpful).
Lastly, and the most minor, there's no point in returning a value from an event handler function because tkinter
simply ignores what they return (and it is what calls them).
Here's your code with modifications to make it work:
#imports
import tkinter
#variables
clicks = 0
#event handler function
def click(event):
global clicks
clicks += 1
print(clicks)
#create gui
window = tkinter.Tk()
button = tkinter.Button(text="click me!")
button.pack()
button.bind("<Button-1>", click)
#run gui
window.mainloop()
Upvotes: 1