[英]How do I get a value from a radio button in tkinter?
我正在Tkinter中创建一个多项选择测验,并且正在使用单选按钮和复选按钮。 对于这个问题,我正在使用单选按钮。 我如何从单选按钮获取值,以便在if语句“计算分数”中进行比较? 计算机返回以下内容:“ calculate_score_1()恰好接受1个参数(给定0)”
另外,如何在类之间传递变量? 我有十个课程,可以回答十个问题,但是当用户正确回答答案时,希望所有人都能够访问变量“分数”。
class Question_1_Window(tk.Toplevel):
'''A simple instruction window'''
def __init__(self, parent):
tk.Toplevel.__init__(self, parent)
self.text = tk.Label(self, width=75, height=4, text = "1) Do you have the time to do at least twenty minutes of prefect duty each week?")
self.text.pack(side="top", fill="both", expand=True)
question_1_Var = IntVar() #creating a variable to be assigned to the radiobutton
Yes_1 = Radiobutton(self, text = "Yes", variable = question_1_Var, value=1, height=5, width = 20)
Yes_1.pack() #creating 'yes' option
#Here we are assigning values to each option which will be used in the validation
No_1 = Radiobutton(self, text = "No", variable = question_1_Var, value=2, height=5, width = 20)
No_1.pack() #creating 'no' option
def calculate_score_1(self):
Enter_1.config(state="disabled")
#self.question_1.config(state="disabled")
if (question_1_Var.get() == 1) and not (question_1_Var.get() == 2):
print("calculate score has worked") #test lines
#score = score + 1
else:
print("not worked") #testlines
Enter_1 = Button(self, text= "Enter", width=10, command = calculate_score_1)
Enter_1.pack()
calculate_score_1
不是实例的方法,而是在__init__
方法内部定义的。 因此,该方法不应具有self
参数。 删除该参数,然后它应该起作用。 如果需要(似乎不需要),您仍然可以使用外部__init__
方法的self
参数。
如果要从另一个类(或实际上是从同一类的另一个方法)访问score
,则必须通过将其定义为self.score = ...
使其成为实例的成员。 然后,您可以像这样访问它: your_question_1_window_instance.score
。
最后,如果您有“十个类别的十个问题”,则应尝试为所有这些问题找到一些共同点,并创建一个通用的超类甚至一个可以参数化以适合所有问题的类别。 您只需要标题,类型(选择一个/选择多个)和答案列表,以及哪些是正确的。 其他所有内容(创建复选框,检查答案等)应始终相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.