[Tutor] command in menu and button
alan.gauld at freenet.co.uk
Tue Nov 22 23:39:35 CET 2005
>>I'm puzzled by the 'command' option in menu and Button of
>>Tkinter. With the following lines,
The command value needs to be a *reference* to a function.
That is not the function call itself but a reference to the function
that will be \called.
Let me illustrate the difference:
def f(): print 'Its me!'
f() # prints the message
g = f # this assigns a reference to f
g() # this now calls that reference,
so calling g() is the same as calling f()
command=os.system("Open my viewer &"))
Here you assign the result of the os.system()
call to command, in fact you want to assign
a reference to a call of os.system which will
be executed when the menu/button is activated.
The more straightforward way to do that is to
define a short function that calls os.system:
And make the menu/button reference callSystem:
Notice no parens, just the name of the function.
Because we can wind up with loads of these little
wrapper functions there is a shortcut called lambda.
With lambda we can avoid defining a new mini function:
command=lambda : os.system("Open my viewer &"))
the thing that follows the lambda is what gets
executed when the widget activates.
Does that help?
More information about the Tutor