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?
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