0

我知道它必须递归地完成(我认为)但不太确定如何。在 def evaluate 中,它必须记录在给出正确答案之前调用了多少次评估。那就是我卡住的地方。

from tkinter import Label, Frame, Entry, Button, LEFT, RIGHT, END
from tkinter.messagebox import showinfo
from random import randrange

# Questions 1 and 2
class Ed(Frame):
    'Simple arithmetic education app'
     def __init__(self,parent=None):
         'constructor'
         Frame.__init__(self, parent)
         self.pack()
         Ed.make_widgets(self)
         Ed.new_problem(self)

     def make_widgets(self):
         'defines Ed widgets'
         self.entry1 = Entry(self,width = 15)
         self.entry1.pack(side = LEFT)
         self.entry2 = Entry(self,width = 15)
         self.entry2.pack(side = LEFT)
         self.button = Button(self, text = "Enter", command = self.evaluate)
         self.button.pack(side = RIGHT)

     def new_problem(self):
         'generates new numbers and decides whether + or -'
         self.entry1.delete(0,END)
         self.entry2.delete(0,END)
         num1 = randrange(0,10)
         num2 = randrange(0,10)
         signNum = randrange(1,3)
         if num1 < num2 and signNum == 2:
             self.new_problem()
         else:
             num1 = str(num1)
             num2 = str(num2)
             if signNum  == 1:
                 sign = "+"
             elif signNum == 2:
                 sign = "-"
             problem = (num1)+sign+(num2)
             self.entry1.insert(0,problem)
     def evaluate(self):
         'handles button "Enter" clicks by comparing answer in entry to correct  result'
         if eval(self.entry1.get()) == int(self.entry2.get()):
             showinfo(title = "Yes!",message = "You got it!")
             self.new_problem()
         else:
             self.entry2.delete(0,END)
     Ed.mainloop()
4

1 回答 1

1

在 init 中添加一个实例变量:

def __init__(self,parent=None):
        'constructor'
        Frame.__init__(self, parent)
        self.pack()
        Ed.make_widgets(self)
        Ed.new_problem(self)
        self.triesCount = 0

并在评估中更新它:

def evaluate(self):
        'handles button "Enter" clicks by comparing answer in entry to correct  result'
        if eval(self.entry1.get()) == int(self.entry2.get()):
            showinfo(title = "Yes!",message = "You got it!")
            self.new_problem()
        else:
            self.entry2.delete(0,END)
            self.triesCount += 1

或者,您可以创建一个单独的问题类来封装所有问题操作和变量,并执行类似的操作来处理尝试计数。

于 2013-02-08T06:43:46.173 回答