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

Peter Otten __peter__ at web.de
Tue Jan 19 13:00:10 CET 2010


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



More information about the Python-list mailing list