如何在python中修复“ RecursionError:超出最大递归深度”

时间:2019-09-10 09:14:03

标签: python-3.x tkinter

我正在编写一个程序,该程序在Python中的随机位置绘制了许多圆圈。 它破裂并吐出“超出最大递归深度”

我试图增加递归限制,但是python shell崩溃并重新启动

class Game():

    def __init__(self, root):
        self. root = root
        self.c = Canvas(root, bg = 'white')
        self.ball = []
        self.start = 0
        self.elapsed = 0
        self.time = 0
        self.i = 0
        self.root.bind('<Key>', self.key)
        self.show()

    def show(self):
        self.start = time.perf_counter()
        for self.i in range(200):
            self.ball.append([Balls(self.c)])
            Balls.create_balls(self)
        self.elapsed = time.perf_counter()
        self.time = self.elapsed - self.start
        print(self.time)
        self.c.pack(fill = BOTH, expand = 1)
        self.update()

    def update(self):
        self.root.after(30, self.update)

    def key(self, event):
        if event.char == 'c':
            #self.ball[57] = self.c.create_oval(Balls.x-12, Balls.y-12, Balls.x+12, Balls.y+12, fill = 'red')
            pass

class Balls(Game):

    def __init__(self, c):
        super(Balls, self).__init__(c)
        self.c = c
        self.x = random.randint(50.0, 450.0)
        self.y = random.randint(50.0, 650.0)

    def create_balls(self):
        self.ball[self.i] = self.c.create_oval(self.x-12, self.y-12, self.x+12, self.y+12, fill = 'blue')

def main():
    root = tkinter.Tk()
    root.geometry('500x700')
    root.title('Balls Game')
    root.resizable(0, 0)
    game = Game(root)
    root.mainloop()

if __name__ == '__main__':
    main()

错误很大,但是同一件事重复了几次。 这是错误:

https://i.stack.imgur.com/bPcbd.png

1 个答案:

答案 0 :(得分:0)

它到底在哪里破裂?

您不应该每次都调用.bind,只需要在开始时绑定一次事件,所以:

    ...
    self.root.bind('<Key>', self.key)
    self.show()

很好。

(也self.ball.append([Balls(self.c)])将一个带有一个Balls对象的列表附加到self.ball列表中,然后调用Balls.create_balls(self),这可能会添加更多的项目。这是否是所需的行为?)