Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Menu command targets function with arguments?

I'm wondering, how would I make a Tkinter (in Python) Menu that targets a function with arguments, such as foo("what")?

def foo(arg):
    print "Foo, %s." % arg

popup = Menu()
popup.add_command(label="Spam!", command=foo("spam")) # Doesn't work.
popup.add_command(label="Turkey!", command=foo("turkey")) # Doesn't work.
popup.post(50, 50)
like image 301
Aqua the SeaWing Avatar asked Jan 13 '15 13:01

Aqua the SeaWing


2 Answers

Command takes a function as argument, but foo("spam") gives the return value of foo when called with argument "spam". As a solution, you can use an anonymous function which calls foo("spam") as argument:

command=lambda: foo("spam")
like image 161
fhdrsdg Avatar answered Sep 17 '22 15:09

fhdrsdg


For this kind of stuff, especially event handlers and commands, an elegant solution is using the functools module's partial() method.

from functools import partial
...
command=partial(foo, "spam")

Partial is said to be faster than using lambda: Differences between functools.partial and a similar lambda?

like image 29
kartikg3 Avatar answered Sep 16 '22 15:09

kartikg3