How can I pass an argument to a Tkinter `bind` callback?

python, tkinter

Solution

In your `bind` function calls, you are actually calling the functions and then binding the result of the function (which is `None`) . You need to directly bind the functions. On solution is to `lambda` for that.

Example -

root.bind('<Return>', lambda event: keypress(key="enter"))
root.bind('a', lambda event: keypress(key="a"))

If you want to propagate the `event` parameter to the `keypress()` function, you would need to define the parameter in the function and then pass it. Example -

def keypress(event, key):
    print key, "pressed"
...
root.bind("<Return>", lambda event: keypress(event, key="enter"))
root.bind("a", lambda event: keypress(event, key="a"))

Problem

I have this code: ``` #!/usr/bin/python3 from Tkinter import * def keypress(key): print key, "pressed" if __name__ == '__main__': root = Tk() root.bind('<Return>', keypress(key="enter")) root.bind('a', keypress(key="a")) root.mainloop() ``` I realize the function is being called as soon as the program starts; how can I make it pass the arguments to the keypress function without invoking it immediately?

Original source

Related problems