向 Tkinter OptionMenu 添加命令? [英] Adding command to a Tkinter OptionMenu?

查看:28
本文介绍了向 Tkinter OptionMenu 添加命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 2.7.8 编写一些代码,其中包括 OptionMenu 小部件.我想创建一个 OptionMenu 在选项更改时调用函数,但我也希望在列表中找到可能的选项,因为我的最终 OptionMenu 将具有多种选择.

I'm writing some code in Python 2.7.8 which includes the OptionMenu widget. 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:

I have used the following code to create an OptionMenu that calls a function:

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

我还发现了以下代码,它创建了一个 OptionMenu,其中包含在列表中找到的选项:

I have also found the following code that creates an OptionMenu with options found in a list:

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

如何创建一个 OptionMenu 来在选项更改时调用函数从列表中获取可能的选项?

How would I create an OptionMenu that calls a function when the option is changed and gets the possible options from a list?

推荐答案

从来不需要直接应用调用,这就是为什么在 2.7 中不推荐使用而在 3.0 中消失的原因.而是使用 *seq 语法.只需将您所做的两件事结合起来.以下似乎可以满足您的需求.

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.

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)

这篇关于向 Tkinter OptionMenu 添加命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆