pythontkinteroptionmenutkinter.optionmenu

add options to option menu with the same command as all the others


Hi im trying to add options to an option menu depending on how many options the user wants, I haven't included the user input part because it isn't necessary in solving the problem. I want all the options in the option menu to call the class optionshow but for some reason i cant get it working please help. Here's the code, thanks for any help in advance.

import tkinter as tk
root = tk.Tk()
root.geometry('1000x600')

class optionshow:
    def __init__(self,p):
        self.p = p.get()
        print(self.p)

option = tk.StringVar()
option.set('Select')
optionmenu = tk.OptionMenu(root, option, 'Select', command=lambda: optionshow(option))
optionmenu.place(x=350, y=20)

choices = ('12345')
for choice in choices:
    optionmenu['menu'].add_command(label=choice, command=tk._setit(option, choice))

root.mainloop()

Solution

  • You instantiate the class only for the 'Entry' option (and not correctly). Why don't you take a different approach and add all the options at once while creating the menu:

    import tkinter as tk
    root = tk.Tk()
    root.geometry('1000x600')
    
    class optionshow():
        def __init__(self,p):
            self.p = p.get()
            print(self.p)
    
    option = tk.StringVar(root)
    option.set('Select')
    choices = ('12345')
    optionmenu = tk.OptionMenu(root, option, 'Select', *choices, command=lambda x: optionshow(option))
    optionmenu.place(x=350, y=20)
    
    root.mainloop()
    

    Note the necessary correction in the command=lambda part.