我正在努力使我的计分系统工作。当我回到教室时,当我更改分数后,它总是忘记,因为它被设置为0。我将如何改变这一点,以使分数适当改变
代码:
import random
from tkinter import *
class TimesTableGUI:
def __init__(self, parent, score = 0):
self.score = score
#chooses a random number
num1 = random.randint(1,10)
num2 = random.randint(1,10)
self.answer = num1 * num2
#making labels
entry_label = Label(parent, text = str(num1) + " * " + str(num2))
entry_label.grid(row = 0, column = 0)
self.e1 = Entry(parent, width = 5)
self.e1.grid(row = 0, column = 1)
b1 = Button(parent, text = "Check Answer", command = self.check_answer)
b1.grid(row = 1, column = 0)
b2 = Button(parent, text = "Next", command = self.new_question)
b2.grid(row = 1, column = 1)
self.b1_output = Label(parent, text = self.score)
self.b1_output.grid(row = 2, column = 0)
def check_answer(self): #callback for Check Answer button
#check if users gets correct answer
f = int(self.e1.get())
if f == self.answer:
self.score +=1
self.b1_output.configure(text = self.score)
else:
self.b1_output.configure(text = self.score)
def new_question(self): #callback for Next button to next question
self.b1_output.configure(text = " ")
radiobuttons = TimesTableGUI(root) #restarts the class for new question
if __name__ == "__main__":
root = Tk()
root.title("Task 3")
radiobuttons = TimesTableGUI(root)
root.mainloop()
问题是,当你调用
radiobuttons = TimesTableGUI(root)
时,分数也会被重置。快速解决方案:在
new_question
中调用radiobuttons = TimesTableGUI(root, score=self.score)
时通过评分更好的解决方案:创建一个重置GUI而不重新初始化整个类的方法
试试这个:
我在一个框架内移动了所有用于该问题的小部件。每次需要显示新问题时,框架都会被销毁并重新创建。我还确保用户在得到正确答案后(针对该问题),不能一直点击
Check Answer
相关问题 更多 >
编程相关推荐