简体   繁体   中英

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM