使用 Python 乌龟鼠标移动获得 "maximum recursion depth exceeded"

Getting "maximum recursion depth exceeded" with Python turtle mouse move

此代码应利用鼠标移动事件在当前鼠标位置绘制一个点:

import turtle

def motion(event):
    x, y = event.x, event.y
    turtle.goto(x-300, 300-y)
    turtle.dot(5, "red")

turtle.pu()
turtle.setup(600, 600)
turtle.hideturtle()
canvas = turtle.getcanvas()
canvas.bind("<Motion>", motion)

如果鼠标移动得非常慢,代码会按预期工作几秒钟或更长时间。然后它抛出:

>>> 
====================== RESTART: C:/code/turtle_move.py 
======================
>>> Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\...\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1698, in __call__
    args = self.subst(*args)
  File "C:\Users\...\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1428, in _substitute
    e.type = EventType(T)
RecursionError: maximum recursion depth exceeded

=============================== RESTART: Shell 
===============================
>>>

非常感谢任何帮助。

问题是当您的事件处理程序仍在处理前一个事件时,一个新事件进入,因此事件处理程序是从事件处理程序内部调用的,这看起来像递归!解决方法是在事件处理程序中禁用事件绑定:

from turtle import Screen, Turtle

def motion(event):
    canvas.unbind("<Motion>")
    turtle.goto(event.x - 300, 300 - event.y)
    turtle.dot(5, "red")
    canvas.bind("<Motion>", motion)

screen = Screen()
screen.setup(600, 600)

turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.penup()

canvas = screen.getcanvas()
canvas.bind("<Motion>", motion)
screen.mainloop()