Python 向 Tkinter OptionMenu 添加命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26744366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding command to a Tkinter OptionMenu?
提问by Paul McDonald
I'm writing some code in Python 2.7.8 which includes the OptionMenuwidget. I would like to create an OptionMenuthat calls a function when the option is changed but I also want the possible options to be found in a list, as my final OptionMenuwill have many options.
我正在用包含OptionMenu小部件的Python 2.7.8 编写一些代码。我想创建一个OptionMenu在选项更改时调用函数的函数,但我也希望在列表中找到可能的选项,因为我的最终OptionMenu选项将有很多选项。
I have used the following code to create an OptionMenuthat 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 OptionMenuwith 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 OptionMenuthat calls a function when the option is changed andgets the possible options from a list?
我将如何创建一个OptionMenu在选项更改时调用函数并从列表中获取可能选项的函数?
采纳答案by Terry Jan Reedy
There is never a need for a direct apply call, which is why is is dreprecated in 2.7 and gone in 3.0. Instead use the *seq syntax. Just combine the two things you did. The following seems to do what you want.
永远不需要直接应用调用,这就是为什么在 2.7 中不推荐使用而在 3.0 中消失的原因。而是使用 *seq 语法。只需将您所做的两件事结合起来。以下似乎做你想做的。
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)

