选择 Python 后立即获得选项菜单的选择 [英] Getting the choice of optionmenu right after selection Python

查看:66
本文介绍了选择 Python 后立即获得选项菜单的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有什么方法可以让我看到用户在显示的列表中选择了什么,比方说:["Apple","Orange","Grapes"]他们选择其中之一?

I was wondering if there is any way for me to see what the User has selected among the list displaying, let's say: ["Apple","Orange","Grapes"] right after they select either one of them?

就像用户点击选项框,然后点击苹果一样,Tkinter 会返回一些东西

Like when user clicks the optionbox, and clicks Apple, Tkinter will return something

然后,如果他将他的选择切换到,比如说,橙色,那么它也会当场返回一些东西.

then if he switches his selection to, let's say, Orange, then that will also return something on the spot.

谢谢!

如何正确放置参数?

from Tkinter import *

def option_changed(a):
    print "the user chose the value {}".format(variable.get())
    print a

master = Tk()

a = "Foo"
variable = StringVar(master)
variable.set("Apple") # default value
variable.trace("w", option_changed(a))

w = OptionMenu(master, variable, "Apple", "Orange", "Grapes")
w.pack()

mainloop()

推荐答案

跟踪 StringVar.

from Tkinter import *

def option_changed(*args):
    print "the user chose the value {}".format(variable.get())
    print a

master = Tk()

a = "Foo"
variable = StringVar(master)
variable.set("Apple") # default value
variable.trace("w", option_changed)

w = OptionMenu(master, variable, "Apple", "Orange", "Grapes")
w.pack()

mainloop()

这里,每当用户从选项菜单中选择一个选项时,都会调用 option_changed.

Here, option_changed will be called whenever the user chooses an option from the option menu.

您可以将 trace 参数包装在 lambda 中以指定您自己的参数.

You can wrap the trace argument in a lambda to specify your own parameters.

def option_changed(foo, bar, baz):
    #do stuff

#...
variable.trace("w", lambda *args: option_changed(qux, 23, "hello"))

这篇关于选择 Python 后立即获得选项菜单的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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