Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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?

like image 509
Pigman168 Avatar asked Oct 16 '25 16:10

Pigman168


1 Answers

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"))
like image 197
Anand S Kumar Avatar answered Oct 18 '25 07:10

Anand S Kumar