I was struggling to find some code that would help me to add values dynamically to a Tkinter Menubutton. After doing a lot of research, I came up with a solution myself and decided to share this piece of knowledge.
Adding items in a menubutton manually is pretty straightforward:
menubutton = Menubutton(root, text = "Select")
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
menubutton.menu.add_checkbutton(label = 'a', variable = var1)
menubutton.menu.add_checkbutton(label = 'b', variable = var2)
menubutton.menu.add_checkbutton(label = 'c', variable = var3)
menubutton.pack()
However, what if one wants to add menu options in Tkinter Menubutton dynamically?
For eg:
If list1 = ['a', 'b', 'c']
, then menu options should be 'a'
, 'b'
, and 'c'
If list1 = ['a', 'c']
, then menu options should be 'a'
and 'c'
This can be done by using a list and a dictionary as follows:
menubutton = Menubutton(root, text = "Select")
menubutton.menu = Menu(menubutton)
menubutton["menu"]= menubutton.menu
# main list holding menu values
list1 = ['a', 'b', 'c']
# Creating a dictionary
dict2 = {}
# Add key-value pairs to dictionary
for i in range(0, len(list1)):
temp = {'var'+str(i): list1[i]}
dict2.update(temp)
# Finally adding values to the actual Menubutton
for i in range(0, len(list1)):
menubutton.menu.add_checkbutton(label = dict2['var'+str(i)], variable = list(dict2.keys())[i])
menubutton.pack()