tkinter how to update optionmenu contents 1

tkinter how to update optionmenu contents

import Tkinter as tk

class App():
    def __init__(self, parent):
        self.parent = parent
        self.options = ['one', 'two', 'three']

        self.om_variable = tk.StringVar(self.parent)
        self.om_variable.trace('w', self.option_select) = tk.OptionMenu(self.parent, self.om_variable, *self.options), row=0)

        self.label = tk.Label(self.parent, text='Enter new option')
        self.entry = tk.Entry(self.parent)
        self.button = tk.Button(self.parent, text='Add option to list', command=self.add_option)

        self.label.grid(column=1, row=0)
        self.entry.grid(column=1, row=1)
        self.button.grid(column=1, row=2)

        self.update_button = tk.Button(self.parent, text='Update option menu', command=self.update_option_menu)
        self.update_button.grid(column=0, row=2)

    def update_option_menu(self):
        menu =["menu"]
        menu.delete(0, "end")
        for string in self.options:
                             command=lambda value=string: self.om_variable.set(value))

    def add_option(self):
         self.entry.delete(0, 'end')
         print self.options

    def option_select(self, *args):
        print self.om_variable.get()

root = tk.Tk()

Here is what the above code is Doing:
1. Create a StringVar to hold the value of the selected option.
2. Create an OptionMenu with the StringVar as the variable.
3. Create a Label, Entry, and Button to add new options to the OptionMenu.
4. Create a Button to update the OptionMenu.
5. Create a trace on the StringVar to print the value of the selected option.
6. Create a function to add a new option to the OptionMenu.
7. Create a function to update the OptionMenu.

Similar Posts