Running commands based on OptionMenu's selection Running commands based on OptionMenu's selection tkinter tkinter

Running commands based on OptionMenu's selection


If you want to run specific methods for options, simply check the sent string and select the method based on the string using if / elif statements:

from tkinter import *def xyz17():    print('xyz17')def abc27():    print('abc27')def qwe90():    print('qwe90')def uio19():    print('uio19')def jkl09():    print('jkl09')def zxc28():    print('zxc28')class Menu(OptionMenu):    def __init__(self, master, status, *options):        self.var = StringVar(master)        self.var.set(status)        OptionMenu.__init__(self, master, self.var, *options, command=self.option_handle)    def option_handle(self, selected):        # above specific case is simply print(selected) but        if selected == "xyz17":            xyz17()        elif selected == "abc27":            abc27()        elif selected == "qwe90":            qwe90()        elif selected == "uio19":            uio19()        elif selected == "jkl09":            jkl09()        elif selected == "zxc28":            zxc28()        # if you specifically want to call methods that has exactly        # the same name as options        # eval(selected + "()")def main():            TopFrame = Frame(root)    TopFrame.pack()    Menu1 = Menu(TopFrame, 'xyz', 'xyz17','abc27','qwe90')    Menu2 = Menu(TopFrame, 'uio', 'uio19','jkl09','zxc28')    Menu1.pack()    Menu2.pack()root = Tk()main()root.mainloop()


One way of running a command based on the option menu selection is to use a dictionary of functions: func_dict = {option: function, ...} and then pass the following function to the command option of the OptionMenu:

def func(value):    func_dict[value]() 

to execute the function corresponding to the chosen option.

Here is an example:

from tkinter import *options = ['xyz', 'xyz17', 'abc27', 'qwe90', 'uio', 'uio19', 'jkl09', 'zxc28']func_dict = {option: lambda opt=option: print(opt) for option in options}class Menu(OptionMenu):    def __init__(self, master, status, *options):        self.var = StringVar(master)        self.var.set(status)        OptionMenu.__init__(self, master, self.var, *options, command=self.func)    def func(self, option):        func_dict[option]()def main():            topFrame = Frame(root)    topFrame.pack()    menu1 = Menu(topFrame, 'xyz', 'xyz17','abc27','qwe90')    menu2 = Menu(topFrame, 'uio', 'uio19','jkl09','zxc28')    menu1.pack()    menu2.pack()root = Tk()main()root.mainloop()