我正在尝试创建一个按钮,该按钮将根据单选按钮选择的选项工作。根据下面的代码,如果选择'Option1'单选按钮,单击测试按钮时应打印出'第一个选项'。对于“选项2”,单击测试按钮时,应打印出“选择的第二个选项”单选按钮。但我总是'第一个选择'。如果有人可以帮忙。
from Tkinter import *
class Select:
def __init__ (self, root):
self.root = root
root.title ('Title')
root.geometry ('100x100')
button1 = Radiobutton (self.root, text = 'Option 1', command = self.option1, value = 1).place (x = 10, y = 10)
button2 = Radiobutton (self.root, text = 'Option 2', command = self.option2, value = 2).place (x = 10, y = 30)
test = Button (self.root, text = 'Run', command = self.test).place (x = 10, y = 70)
self.root.mainloop()
def option1 (self):
print ' Option 1'
def option2 (self):
print ' Option 2'
def test (self):
if self.option1:
print ' 1st option selected'
elif self.option2:
print '2nd option selected'
else:
print 'No option selected'
Select(Tk()).test()
答案 0 :(得分:1)
if self.option1:
总是如此,因为你问的是self.option1 - 方法指针 - 是否为非零。你甚至没有调用函数(在名称后需要括号),但如果你是,它将返回print
语句的结果,这也不是你想要的。在option1()(以及option2())中需要发生的是你设置一个可以从函数外部访问的标志,以表明它已经运行。
例如:
from Tkinter import *
class Select:
def __init__ (self, root):
self.root = root
root.title ('Title')
root.geometry ('100x100')
button1 = Radiobutton (self.root, text = 'Option 1', command = self.option1, value = 1).place (x = 10, y = 10)
button2 = Radiobutton (self.root, text = 'Option 2', command = self.option2, value = 2).place (x = 10, y = 30)
test = Button (self.root, text = 'Run', command = self.test).place (x = 10, y = 70)
self.flag = 0
self.root.mainloop()
def option1 (self):
print ' Option 1'
self.flag = 1
def option2 (self):
print ' Option 2'
self.flag = 2
def test (self):
if self.flag == 1:
print '1st option selected'
elif self.flag == 2:
print '2nd option selected'
else:
print 'No option selected'
Select(Tk()).test()