By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,551 Members | 1,127 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,551 IT Pros & Developers. It's quick & easy.

Tkinter: how to fill values in OptionMenu dynamically

P: n/a
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?
--
Jeffrey Barish
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
In article <ma**************************************@python.o rg>,
Jeffrey Barish <je********@starband.net> 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?


I see other postings showing two common solutions. A third is to try
RO.Wdg from my RO package
<http://www.astro.washington.edu/rowen/ROPython.html>. It may be a bit
more stuff than you want, but RO.Wdg.OptionMenu allows you to set new
values whenever you want and it includes improved versions of most of
the other widgets.

-- Russell
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.