pmw menu item's 'command' attribute

Peter Otten __peter__ at web.de
Thu Aug 28 17:10:15 EDT 2003


"Tina Li" <tina_li23 AT hotmail DOT com> wrote:

> for size in ('tiny', 'small', 'average', 'big', 'huge'):
>             self.menuBar.addmenuitem('Size', 'command', 'Set size to ' +
> size,
>                     command = lambda: cmd.do('change size ' + size),
>                     label = size)

The variable size in the lambda expression is bound to the global variable
size, so if you do

size = 42

later, the menu command will even raise an exception.
Solution:

command=lambda size=size: cmd.do('change size ' + size)

This creates a local variable size that defaults to the same string that the
outer size variable is bound to when the lambda expression is created.
(Don't know if the explanation works, but the code should :-)

Peter





More information about the Python-list mailing list