Tkinter Menu command
Fredrik Lundh
fredrik at pythonware.com
Sat Jul 13 12:22:02 EDT 2002
Raimo Tuisku wrote:
> Is it possible to pass arguments to a method which is executed after
> event? I am trying to do so with add_command method from Menu
> widget to avoid writing separate method for every case.
> #From class App:
> self.mb = Menubutton(self.frame, text="Color")
> self.mb.grid()
> self.mb.menu = Menu(self.mb,tearoff=0)
> self.mb['menu'] = self.mb.menu
> self.colors=['red','green','blue']
> for item in self.colors:
> self.mb.menu.add_command
> (label=item,command=lambda :self.set_color(item))
> # Even this doesn't work. Apparently it always uses
> # self.set_color('blue'). (self.label colors to blue)
for item in self.colors:
self.mb.menu.add_command
(label=item,command=lambda :self.set_color(item))
when the lambda is called, its body will pick up the *current*
value of the "item" variable. (it's a reference to something that
lives in another namespace, not a reference to its value)
to get the value it had when you created the lambda, you
need to use explicit name binding:
self.mb.menu.add_command(
label=item,
command=lambda item=item:self.set_color(item)
)
</F>
More information about the Python-list
mailing list