Tk Dynamic Menus problem

Jeremy Bowers jerf at jerf.org
Wed Jul 24 18:10:58 EDT 2002


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()




More information about the Python-list mailing list