I want to bind a method to an event using Tkinter, but I don't need the event object passed by the 'bind'-method. Some code for clarity:
from Tkinter import *
root = Tk()
def callback(event):
print 'clicked!'
frame = Frame(root, width=100, height=100)
frame.bind('<Button-1>', callback)
frame.pack()
root.mainloop()
Here, the argument event in callback is unnecessary. Is there any solution or workaround to prevent the bind-method from passing the event object?
What I mean is, can i call this:
def callback2():
print 'clicked!'
in a binding? Something like:
frame.bind('<Button-2>', callback2)
(which is actually not working, because bin passes event, but callback2 takes no arguments).
You have three broad options, as I see it (in order of increasing complexity):
Use the ignored-by-convention variable name _
:
def callback2(_):
...
Wrap the callback when you bind it:
frame.bind('...', lambda event: callback2())
Write a decorator to ignore the event
parameter for you:
def no_event(func):
@functools.wraps(func)
def wrapper(event):
return func()
return wrapper
then apply it to callback methods that don't need the event:
@no_event
def callback2():
...