此代码应利用鼠标运动事件在当前鼠标位置绘制一个点:
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
===============================
>>>
非常感谢您的帮助。
答案 0 :(得分:2)
问题在于,当事件处理程序仍在处理前一个事件时,会出现一个新事件,因此该事件处理程序是从事件处理程序内部调用的,看起来像是递归!解决方法是在事件处理程序内部禁用事件绑定:
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()