tkinter how to update optionmenu contents

Solutions on MaxInterview for tkinter how to update optionmenu contents by the best coders in the world

showing results for - "tkinter how to update optionmenu contents"
Sofie
12 May 2016
1import Tkinter as tk
2
3class App():
4    def __init__(self, parent):
5        self.parent = parent
6        self.options = ['one', 'two', 'three']
7
8        self.om_variable = tk.StringVar(self.parent)
9        self.om_variable.set(self.options[0])
10        self.om_variable.trace('w', self.option_select)
11
12        self.om = tk.OptionMenu(self.parent, self.om_variable, *self.options)
13        self.om.grid(column=0, row=0)
14
15        self.label = tk.Label(self.parent, text='Enter new option')
16        self.entry = tk.Entry(self.parent)
17        self.button = tk.Button(self.parent, text='Add option to list', command=self.add_option)
18
19        self.label.grid(column=1, row=0)
20        self.entry.grid(column=1, row=1)
21        self.button.grid(column=1, row=2)
22
23        self.update_button = tk.Button(self.parent, text='Update option menu', command=self.update_option_menu)
24        self.update_button.grid(column=0, row=2)
25
26    def update_option_menu(self):
27        menu = self.om["menu"]
28        menu.delete(0, "end")
29        for string in self.options:
30            menu.add_command(label=string, 
31                             command=lambda value=string: self.om_variable.set(value))
32
33    def add_option(self):
34         self.options.append(self.entry.get())
35         self.entry.delete(0, 'end')
36         print self.options
37
38    def option_select(self, *args):
39        print self.om_variable.get()
40
41
42root = tk.Tk()
43App(root)
44root.mainloop()
45