Tkinter: how to fill values in OptionMenu dynamically

Peter Otten __peter__ at web.de
Thu Apr 22 08:46:21 EDT 2004


Jeffrey Barish wrote:

> Is there a way to fill the values in an OptionMenu dynamically?  I need
> something like the add_command method from Menu.  Is there a better way
> to implement a pull-down list?

OptionMenu wasn't designed with this usage pattern in mind. But you can
force it:

import Tkinter as tk

class OptionMenu(tk.OptionMenu):
    def __init__(self, *args, **kw):
        self._command = kw.get("command")
        tk.OptionMenu.__init__(self, *args, **kw)
    def addOption(self, label):
        self["menu"].add_command(label=label,
            command=tk._setit(variable, label, self._command))

if __name__ == "__main__":
    root = tk.Tk()

    variable = tk.StringVar()
    variable.set("beta")

    optionMenu = OptionMenu(root, variable, "alpha", "beta", "gamma")
    optionMenu.pack()

    btn = tk.Button(root, text="Add",
        command=lambda: optionMenu.addOption("DELTA"))
    btn.pack()

    root.mainloop()

If you are looking for something more robust/complete than my little adhoc
subclass, you might have a look at the Python Megawidgets (pmw.sf.net).

Peter




More information about the Python-list mailing list