[英]Adding command to a Tkinter OptionMenu?
I'm writing some code in Python 2.7.8 which includes the OptionMenu
widget. 我正在Python 2.7.8中编写一些代码,其中包括OptionMenu
小部件。 I would like to create an OptionMenu
that calls a function when the option is changed but I also want the possible options to be found in a list, as my final OptionMenu
will have many options. 我想创建一个OptionMenu
,当更改选项时会调用一个函数,但我也希望在列表中找到可能的选项,因为我的最终OptionMenu
将具有许多选项。
I have used the following code to create an OptionMenu
that calls a function: 我已使用以下代码创建一个调用函数的OptionMenu
:
from Tkinter import*
def func(value):
print(value)
root = Tk()
var = StringVar()
DropDownMenu=OptionMenu(root, var, "1", "2", "3", command=func)
DropDownMenu.place(x=10, y=10)
root.mainloop()
I have also found the following code that creates an OptionMenu
with options found in a list: 我还发现了以下代码,该代码创建一个OptionMenu
并在列表中找到选项:
from Tkinter import*
root = Tk()
Options=["1", "2", "3"]
var = StringVar()
DropDownMenu=apply(OptionMenu, (root, var) + tuple(Options))
DropDownMenu.place(x=10, y=10)
root.mainloop()
How would I create an OptionMenu
that calls a function when the option is changed and gets the possible options from a list? 我将如何创建一个OptionMenu
调用时更改选项的功能,并从列表中获取可能的选项?
There is never a need for a direct apply call, which is why is is dreprecated in 2.7 and gone in 3.0. 永远不需要直接应用调用,这就是在2.7中弃用并且在3.0中弃用的原因。 Instead use the *seq syntax. 而是使用* seq语法。 Just combine the two things you did. 只需结合您所做的两件事即可。 The following seems to do what you want. 以下内容似乎可以满足您的要求。
from tkinter import *
def func(value):
print(value)
root = Tk()
options = ["1", "2", "3"]
var = StringVar()
drop = OptionMenu(root, var, *options, command=func)
drop.place(x=10, y=10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.