Search code examples
python-2.7eventstkinterevent-binding

How can I prevent Tkinter from passing the event object in a binding? Is there any workaround to do this?


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


Solution

  • You have three broad options, as I see it (in order of increasing complexity):

    1. Use the ignored-by-convention variable name _:

      def callback2(_):
          ...  
      
    2. Wrap the callback when you bind it:

      frame.bind('...', lambda event: callback2())
      
    3. 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():
          ...