Tk Dynamic Menus problem

Greg Krohn ("X", "@") "gkrohnXvolucris.8m.com".replace
Wed Jul 24 19:42:22 EDT 2002


"Jeremy Bowers" <jerf at jerf.org> wrote in message
news:SBF%8.104617$_51.86102 at rwcrnsc52.ops.asp.att.net...
> For the following Tk test program, I am having a problem. A dynamic menu
> is being generated every time I click the "Test" menu, and three menu
> options are generated, each with a different command. However, if you
> click on any of the three options, the *third* command is executed, so all
> menu options print 3. I expect the menu options to do what they say.
>
> I'd rather do it this way then fiddle with the menu options on each drop
> down, as that's complicated when I can't guarentee the same number of
> options on each drop down. (There are good reasons for that that make UI
> sense in the context of the program this is getting used in.)
>
> I've tried a number of workarounds, but none seem to work. Is this a bug
> in Tk or Tkinter? (It doesn't seem like this should be impossible...)
>
> ---------
>
> from Tkinter import *
>
> def printFunc(s):
>     print s
>
> class App:
>     def __init__(self, master):
>         self.frame = Frame(master, width = 200, height = 40)
>         self.frame.pack()
>
>         self.menu = Menu(master)
>         master.config(menu = self.menu)
>
>         self.dynmenu = Menu(self.menu, postcommand = self.updateMenu)
>         self.menu.add_cascade(label="Test", menu = self.dynmenu)
>
>     def updateMenu(self):
>         self.dynmenu.delete(0, 99) # big num to get everything
>
>         for i in [1, 2, 3]:
>             self.dynmenu.add_command(label = "Print %i" % i,
>                                      command = lambda: printFunc(i))
>
> root = Tk()
> app = App(root)
> root.mainloop()
>

I'm not exactly sure why it's printing '3', but you do have a scoping
problem there.
Replace 'lambda: printFunc(i)' with 'lambda i=i: printFunc(i)'. Supplying i
as a keyword arg for the lambda brings i into the labmda's scope.

greg





More information about the Python-list mailing list