根据OptionMenu的选择运行命令

时间:2018-01-25 13:38:56

标签: python python-3.x tkinter drop-down-menu optionmenu

如何调整此设置,以便从菜单中选择xyz17时运行函数xyz17()

我知道command = xyz17,但我不确定如何制作动态,以便取决于菜单选择。

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)

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

请注意,每个打印值的函数仅作为示例,我希望代码能够运行函数本身。我意识到了这一点:

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,value):
        print (value)

但是,这与我的场景无关,因为它只是获取值并打印出来,我希望它能够实际运行该函数。

2 个答案:

答案 0 :(得分:1)

如果要为选项运行特定方法,只需检查发送的字符串,然后使用if / elif语句选择基于字符串的方法:

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

答案 1 :(得分:0)

基于选项菜单选择运行命令的一种方法是使用函数字典:func_dict = {option: function, ...},然后将以下函数传递给command的{​​{1}}选项:

OptionMenu

执行与所选选项对应的功能。

以下是一个例子:

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