Tkinter Menus
Tim Daneliuk
tundra at tundraware.com
Mon Dec 16 11:40:07 EST 2002
Eric Brunel wrote:
> Tim Daneliuk wrote:
>
>
>>Justin Shaw wrote:
>><SNIP>
>>
>>>
>>>This version invokes callback when the menu is created:
>>>m.add_command(label='Call %s' % (label=" ...", callback(i+1))
>>>
>>>and so is essentially the same as
>>>m.add_command(label='Call %s' % (label=" ...", None)
>>>
>>>as apposed to the other version which creates a lambda function at menu
>>>creation time that gets called when the menu is clicked.
>>
>>
>>Yes, that's what I suspected. But, what I'm trying to understand is
>>the language semantics here: *why* do the two forms behave the way
>>they do -i.e., What is it about the lambda form that defers
>>execution until the time when a menu item is selected?
>
>
> Because the purpose of lambda's is exactly that: create on the fly small
> functions that can be used as callbacks for Tkinter's menus, buttons, or
> wherever else you need to pass a function.
>
> When you write:
> lambda x: <expr using x>
> it's exactly the same than writing
> def f(x):
> return <expr using x>
> and use f.
>
> Using a simpler example than the one we started with, the following two
> codes do the same thing:
>
> ---Code 1---------------------
> def myPrint(x):
> print '>>>', x
> ...
> def myCallback():
> myPrint(76 + 23)
> b = Button(..., command=myCallback)
> b.pack()
> ...
> ------------------------------
>
> ---Code 2---------------------
> def myPrint(x):
> print '>>>', x
> ...
> b = Button(..., command=lambda: myPrint(76 + 23))
> b.pack()
> ...
> ------------------------------
>
> So the evalution of myPrint(76 + 23) is deferred is the second code for
> exactly the same reason than in the first one: because it's included in a
> function. In the first code, the function is explicit and named myCallback;
> in the second one, the function is implicitely created by the lambda.
>
> HTH
Very clear - many thanks...
--
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com
More information about the Python-list
mailing list