Search code examples
pythontkintertkinter.optionmenu

Python tkinter change OptionMenu during runtime


My second dropdown list is dependent on my first dropdown list. I can make it work by creating a second OptionMenu that overwrites the first OptionMenu. The following code works.

However, I'm looking for way that will use the same OptionMenu, but will substitute in a new list for the second_choice_proxylist in the second_list.

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry('400x275')

def option_selected(event):
        if event == option_list[0]:
            option_list2 = first_sublist
        if event == option_list[1]:
            option_list2 = second_sublist
        
        second_list = ttk.OptionMenu(root, second_choice, 'foo or bar', *option_list2)
        second_list.grid(column=2, row=2, sticky=(W, E))

choice_var = StringVar(root)
choice_var.set("Option 1") 
option_list = ["Option 1", "Option 2"]
first_sublist = ['foo1', 'foo2']
second_sublist = ['bar1', 'bar2']

first_list = ttk.OptionMenu(root, choice_var, 'Make a Choice', *option_list, command=option_selected)
first_list.grid(column=2, row=1)
second_choice = StringVar()
second_choice_proxylist = ['Make First Selection First']
second_list = ttk.OptionMenu(root, second_choice, 'Make a Choice', *second_choice_proxylist)
second_list.grid(column=2, row=2)

first_label = ttk.Label(root, text = 'Choose Here First')
first_label.grid(column=1, row=1)
second_label = ttk.Label(root, text = 'Choose Here Second')
second_label.grid(column=1, row=2)

root.mainloop()

Solution

  • You can use .set_menu() to update the option values of second_list:

    def option_selected(event):
        if event == option_list[0]:
            option_list2 = first_sublist
        elif event == option_list[1]:
            option_list2 = second_sublist
    
        second_list.set_menu('foo or bar', *option_list2)