With the code I currently have, when the program starts, I can select from 3 options, and have that option printed to the console. I can also have text entered into the text entry, be added to the optionMenu list by pressing the button.
By adding the new option, it breaks the optionMenu, and I am no longer able to get the selected option from the optionMenu.
I have tried looking through tkinter documentation (the little I could find), but have not found info relating to my problem.
import tkinter
category_list = ['Option A', 'Option B','Option C']
def add_To_List():
entry = entry_Right.get()
if entry not in category_list:
option_Left_StringVar.set('')
menu_left = option_Left["menu"]
menu_left.delete(0, "end")
category_list.append(entry)
for choice in category_list:
menu_left.add_command(label=choice,
command=tkinter._setit(option_Left_StringVar, choice))
def option_Left_Function(selection):
print(selection)
#----GUI----
root = tkinter.Tk()
frame_Left = tkinter.Frame(root)
frame_Left.grid(column=0, row=0, sticky='w')
option_Left_StringVar = tkinter.StringVar(frame_Left)
option_Left = tkinter.OptionMenu(frame_Left, option_Left_StringVar,
*category_list, command=option_Left_Function)
option_Left.grid(column=0, row=0, sticky='w')
frame_Right = tkinter.Frame(root)
frame_Right.grid(column=1, row=0, sticky='e')
entry_Right = tkinter.Entry(frame_Right)
entry_Right.grid(column=1, row=0, sticky='w')
button_Right = tkinter.Button(frame_Right, text='Add to list',
command=add_To_List)
button_Right.grid(column=2, row=0, sticky='w')
root.mainloop()
The furthest I was able to come (as you see in the code above), was to add a new option to the optionMenu, but this doesn't help when I cannot then access the selection of the optionMenu in the code.
I would really appreciate help on this issue, thanks.
You have to add option_Left_Function
as third argument
command=tkinter._setit(option_Left_StringVar, choice, option_Left_Function)
Using print(tkinter.__file__)
you can get path to source code and you can see this in this file.
BTW: you don't have to delete old items. You can add only new item.
def add_To_List():
entry = entry_Right.get()
if entry not in category_list:
option_Left_StringVar.set('')
menu_left = option_Left["menu"]
menu_left.add_command(label=entry,
command=tkinter._setit(option_Left_StringVar, entry, option_Left_Function))
category_list.append(entry)