我是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方法为StingVar做这样的事情:
#!/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)
我做错了什么?
请注意,我不想在下拉菜单中使用任何按钮来确认选择。
你能提出一些建议吗?
答案 0 :(得分:9)
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)
这应该按照你的意愿行事。