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?
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With