Getting “maximum recursion depth exceeded” with Python turtle mouse move

北城以北 提交于 2019-12-24 21:23:21

问题


This code should utilize mouse motion events to draw a dot at the current mouse position:

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)

The code works as expected for a few seconds or longer if the mouse is moved very slowly. Then it throws:

>>> 
====================== 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 
===============================
>>>

Any help is much appreciated.


回答1:


The problem is that a new event comes in while your event hander is still processing the previous event, so the event handler gets called from inside the event handler which looks like a recursion! The fix is to disable the event binding while inside the event handler:

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()


来源:https://stackoverflow.com/questions/53055573/getting-maximum-recursion-depth-exceeded-with-python-turtle-mouse-move

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!