TKinter的OptionMenu:如何获取所选选择?

9

我对Python和Tkinter都比较新手,但我需要创建一个简单的表单,需要使用下拉菜单。

我尝试做类似于以下的事情:

#!/usr/bin python
import sys

from Tkinter import *

# My frame for form
class simpleform_ap(Tk):

    def __init__(self,parent):
        Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        # Dropdown Menu
        optionList = ["Yes","No"]
        self.dropVar=StringVar()
        self.dropVar.set("Yes") # default choice
        self.dropMenu1 = OptionMenu(self, self.dropVar, *optionList)
        self.dropMenu1.grid(column=1,row=4)
        print self.dropVar.get()

def create_form(argv):
    form = simpleform_ap(None)
    form.title('My form')
    form.mainloop()

if __name__ == "__main__":
  create_form(sys.argv)

然而,我所输出的始终是默认值,而不是我从下拉列表中选择的值。
我尝试使用trace方法对StringVar进行操作,做如下操作:
#!/usr/bin python
import sys
from Tkinter import *

# My frame for form
class simpleform_ap(Tk):

    def __init__(self,parent):
        Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        # Dropdown Menu
        optionList = ["Yes","No"]
        self.dropVar=StringVar()
        self.dropVar.set("Yes") # default choice
        self.dropMenu1 = OptionMenu(self, self.dropVar, *optionList)
        self.dropMenu1.grid(column=1,row=4)
        self.dropVar.trace("w",self.get_selection)
        print self.dropVar.get()


    def get_selection(self):
        print "Selected: "+ self.dropVar.get()

def create_form(argv):
    form = simpleform_ap(None)
    form.title('My form')
    form.mainloop()

if __name__ == "__main__":
    create_form(sys.argv)

但是我收到了以下错误信息:
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib64/python2.6/lib-tk/Tkinter.py", line 1410, in __call__
    return self.func(*args) TypeError: get_selection() takes exactly 1 argument (4 given)

我做错了什么吗?

请注意,我不想使用任何按钮来确认下拉菜单中的选择。

能否给予一些建议?

1个回答

16

OptionMenu内置了command选项,可以将当前的menu状态传递给一个函数。看下面的例子:

#!/usr/bin python
import sys
from Tkinter import *

# My frame for form
class simpleform_ap(Tk):

    def __init__(self,parent):
        Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
        self.grid()

    def initialize(self):
        # Dropdown Menu
        optionList = ["Yes","No"]
        self.dropVar=StringVar()
        self.dropVar.set("Yes") # default choice
        self.dropMenu1 = OptionMenu(self, self.dropVar, *optionList,
                                    command=self.func)
        self.dropMenu1.grid(column=1,row=4)

    def func(self,value):
        print value


def create_form(argv):
    form = simpleform_ap(None)
    form.title('My form')
    form.mainloop()

if __name__ == "__main__":
    create_form(sys.argv)

这应该能够满足您的要求。


2
非常感谢!你真的让我的一天变得美好 :) - Jackkilby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接