Updating an OptionMenu every time the text file it reads from is updated (Tkinter)

Dr. Benjamin David Clarke moekaveli at gmail.com
Tue Jan 19 16:23:35 EST 2010


On Jan 19, 7:00 am, Peter Otten <__pete... at web.de> wrote:
> Dr. Benjamin David Clarke wrote:
>
> > I currently have a program that reads in values for an OptionMenu from
> > a text file. I also have an option to add a line to that text file
> > which corresponds to a new value for that OptionMenu. How can I make
> > that OptionMenu update its values based on that text file without
> > restarting the program? In other words, every time I add a value to
> > the text file, I want the OptionMenu to immediately update to take
> > note of this change. I'll provide code if needed.
>
> Inferred from looking into the Tkinter source code:
>
> # python 2.6
> import Tkinter as tk
>
> root = tk.Tk()
>
> var  = tk.StringVar()
> var.set("One")
>
> optionmenu = tk.OptionMenu(root, var, "One", "Two", "Three")
> optionmenu.grid(row=0, column=1)
>
> def add_option():
>     value = entry_add.get()
>     menu = optionmenu["menu"]
>     variable = var
>     command = None # what you passed as command argument to optionmenu
>     menu.add_command(label=value,
>                      command=tk._setit(variable, value, command))
>
> label_show = tk.Label(root, text="current value")
> label_show.grid(row=1, column=0)
> entry_show = tk.Entry(root, textvariable=var)
> entry_show.grid(row=1, column=1)
>
> label_add = tk.Label(root, text="new option")
> label_add.grid(row=2, column=0)
> entry_add = tk.Entry(root)
> entry_add.grid(row=2, column=1)
>
> button_add = tk.Button(root, text="add option",
>                    command=add_option)
> button_add.grid(row=2, column=2)
>
> root.mainloop()
>
> Peter

The problem turned out to be fairly simple. I just had to get a little
creative with nesting my functions and add or remove the option from
the OptionMenu right after adding/removing to the text file. Thanks
for pointing me in the right direction.



More information about the Python-list mailing list