I made a small tkinter window which has dropdown options and I wish to add new options to it, the code below adds options to the list, but I cannot select any when i click on them. The command attached with the optionmenu doesn't print the newly added options on clicking, the predefined ones work just fine. I cannot find the bug in the code yet.
enter code here
# CHECK OPTIONS MENU
from tkinter import *
def add_op(e,op):
choice=e.get()
var=StringVar(root)
options.append(e.get())
option['menu'].add_command(label=choice, command=var.set(choice)) #add new option here
op.grab_release()
op.destroy()
def add_option():
op=Toplevel(root)
Label(op,text='Enter new option :').grid(row=1,column=1)
e=Entry(op)
e.grid(row=1,column=2)
Button(op,text='SUBMIT',command=lambda: add_op(e,op)).grid(row=2,column=2)
def comm(var):
print(var)
if(var=='add_new'):
add_option()
root=Tk()
root.title('checking options')
Label(root,text='something ').grid(row=1,column=1)
options=['add_new','one','two','three','four']
var=StringVar(root)
var.set(options[2])
option=OptionMenu(root,var,*options,command=comm)
option.grid(row=1,column=2,pady=5,sticky='ew')
root.mainloop()
Just re-create the option
widget again in the add_op
function.
def add_op(e,op):
choice=e.get()
var=StringVar(root)
options.append(e.get())
########## Changes ##############
var.set(options[2])
option=OptionMenu(root,var,*options,command=comm)
option.grid(row=1,column=2,pady=5,sticky='ew')
#################################
op.grab_release()
op.destroy()