0

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()
Sugato
  • 35
  • 8

1 Answers1

1

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()
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
  • thanks, that worked like a charm, although I wanted to know what was the error while using `option['menu'].add_command(label=choice, command=var.set(choice))` . do u have any idea? – Sugato Jun 08 '20 at 04:47