How do i populate tkinter drop-down box with new data everytime i pressed "refresh"? How do i populate tkinter drop-down box with new data everytime i pressed "refresh"? tkinter tkinter

How do i populate tkinter drop-down box with new data everytime i pressed "refresh"?


An approach could be to destroy the old one and place a new one at the same position.

If you use place, then you can simply place the new one at the same coordinate, example

from tkinter import *def refresh():    global optionmenu    data=['new','data']    optionmenu.destroy()    option.set('')    optionmenu=OptionMenu(root,option,*data)    optionmenu.place(x=100,y=50)root=Tk()option=StringVar()data=['hello','world']optionmenu=OptionMenu(root,option,*data)optionmenu.place(x=100,y=50)button=Button(root,text='Refresh',command=refresh)button.pack(padx=100,pady=100)root.mainloop()

If you use pack or grid, you will need to have a container Frame that will hold the position, example

from tkinter import *def refresh():    global optionmenu    data=['new','data']    optionmenu.destroy()    option.set('')    optionmenu=OptionMenu(op_frame,option,*data)    optionmenu.pack()root=Tk()option=StringVar()data=['hello','world']op_frame=Frame(root)op_frame.pack()optionmenu=OptionMenu(op_frame,option,*data)optionmenu.pack()button=Button(root,text='Refresh',command=refresh)button.pack(padx=100,pady=10)root.mainloop()

UPDATE

You could also do it by accessing the menu of the OptionMenu, clearing it out and rewriting all the options.

def refresh():    global optionmenu    data=['new','data']    menu=optionmenu['menu']    menu.delete(0,END)    for d in data:        menu.add_command(label=d,command=lambda val=d: option.set(val))