gpt4 book ai didi

python - 根据 OptionMenu 的选择运行命令

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:50 24 4
gpt4 key购买 nike

如何调整此设置,以便在从菜单中选择 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)

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

最佳答案

如果您想运行选项的特定方法,只需检查发送的字符串并使用 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()

关于python - 根据 OptionMenu 的选择运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48444246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com