4

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Pigman168
  • 399
  • 1
  • 4
  • 13

1 Answers1

7

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"))
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176