简体   繁体   中英

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)

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")

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM