Python 如何为复选按钮赋值并使用它们计算分数?
我正在用Tkinter写一个选择题quiuz,在我的一些问题中使用了复选按钮,用户可以选择“所有正确答案”。我已经创建了用于存储复选按钮值的变量(开/关值-1/0)。然而,计算机似乎不理解变量的值,因此在“计算分数”if语句中,计算机无法进行比较,因为它无法识别复选按钮的值Python 如何为复选按钮赋值并使用它们计算分数?,python,variables,tkinter,logic,Python,Variables,Tkinter,Logic,我正在用Tkinter写一个选择题quiuz,在我的一些问题中使用了复选按钮,用户可以选择“所有正确答案”。我已经创建了用于存储复选按钮值的变量(开/关值-1/0)。然而,计算机似乎不理解变量的值,因此在“计算分数”if语句中,计算机无法进行比较,因为它无法识别复选按钮的值 class Question_5_Window(tk.Toplevel): '''A simple instruction window''' def __init__(self, parent):
class Question_5_Window(tk.Toplevel):
'''A simple instruction window'''
def __init__(self, parent):
tk.Toplevel.__init__(self, parent)
self.text = tk.Label(self, width=100, height=4, text = "5) What would you do if you were walking to class and you saw a first year crying? Tick all correct answers.")
self.text.pack(side="top", fill="both", expand=True)
question_5_Var1 = IntVar()
question_5_Var2 = IntVar()
question_5_Var3 = IntVar()
A_5 = Checkbutton(self, text = "Keep walking", variable = question_5_Var1, onvalue = 1, offvalue = 0, height=5, width = 20)
A_5.pack()
B_5 = Checkbutton(self, text = "Take them to guidance", variable = question_5_Var2, onvalue = 1, offvalue = 0, height=5, width = 20)
B_5.pack()
C_5 = Checkbutton(self, text = "Talk to them to resolve issue", variable = question_5_Var3, onvalue = 1, offvalue = 0, height=5, width = 20)
C_5.pack()
def calculate_score():
if (question_5_Var2 == True) and (question_5_Var3 == True):
print("calculate score has worked")
else:
print("not worked")
Enter_5 = Button(self, text= "Enter", width=10, command = calculate_score)
Enter_5.pack()
def flash(self):
'''make the window visible, and make it flash temporarily'''
# make sure the window is visible, in case it got hidden
self.lift()
self.deiconify()
# blink the colors
self.after(100, lambda: self.text.configure(bg="black", fg="white"))
self.after(500, lambda: self.text.configure(bg="white", fg="black"))
您的
question\u 5\u VarX
变量属于IntVar
类型,因此它们在任何情况下都不会是True
。您应该使用get()
方法检查它们的值。请注意,该值将是一个int
,但您可以像使用布尔值一样使用它
if question_5_Var2.get() and question_5_Var3.get() and not question_5_Var1.get():
(您可能还想检查第一个答案是否未被选中。)问题5\u Var2
是一个IntVar
,为什么它应该等于True
?您可能希望改为使用get()
检查其值。很抱歉,我最初将它们设为“1”而不是“True”,但更改了它们以查看会发生什么。@user3056786重要的是使用get()
而不是比较变量本身。那么,这行得通吗?