我正在创建一个在tkinter画布中使用turtle的简单程序,以允许用户使用鼠标进行绘制。绘图函数似乎工作正常但是在绘制一点之后程序停止并调用RecursionError。
from turtle import *
import tkinter as tk
box=tk.Tk()
canv=ScrolledCanvas(box)
canv.pack()
screen=TurtleScreen(canv)
p=RawTurtle(screen)
p.speed(0)
def draw(event):
p.goto(event.x-256,185-event.y) #The numbers are here because otherwise the turtle draws off center. Might be different depending on computer.
canv.bind('<B1-Motion>', draw)
box.mainloop()
理论上这应该很好,但它调用的是RecursionError。我迷失了,除了可能在try循环中包装函数之外我还能做些什么来防止这种情况。任何帮助将非常感激。
Python Shell中的输出:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\Charlie\Desktop\demo.py", line 17, in draw
p.speed(0)
File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2174, in speed
self.pen(speed=speed)
File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2459, in pen
self._update()
File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2660, in _update
self._update_data()
File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2651, in _update_data
self._pencolor, self._pensize)
File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 545, in _drawline
self.cv.coords(lineitem, *cl)
File "<string>", line 1, in coords
RecursionError: maximum recursion depth exceeded while calling a Python object
我花了很多时间寻找答案,据我所知,没有一个地方很容易找到。这是我在这个网站上的第一个问题所以请原谅我,如果我做错了。
答案 0 :(得分:1)
我无法重现您的递归错误,但我之前已经看过了。通常在事件处理程序忙于处理事件时有新事件进入的情况下。 (这就是为什么它看起来像递归。)通常的解决方法是关闭事件处理程序内的事件处理程序。尝试一下,看看它是否适合你:
from turtle import RawTurtle, ScrolledCanvas, TurtleScreen
import tkinter as tk
box = tk.Tk()
canv = ScrolledCanvas(box)
canv.pack()
screen = TurtleScreen(canv)
p = RawTurtle(screen)
p.speed('fastest')
def draw(x, y):
p.ondrag(None)
p.setheading(p.towards(x, y))
p.goto(x, y)
p.ondrag(draw)
p.ondrag(draw)
box.mainloop()
答案 1 :(得分:0)
我了解绘图一段时间后,您将遇到递归错误。
遇到此错误时通常要做的是导入sys模块,调用
sys.setrecursionlimit()
,我在括号中放了很多。这将使递归限制更高,并且您很可能不会再遇到此错误。
下面是经过修改的脚本,希望它对您有用。
from turtle import *
import tkinter as tk
import sys
sys.setrecursionlimit(10000)
box=tk.Tk()
canv=ScrolledCanvas(box)
canv.pack()
screen=TurtleScreen(canv)
p=RawTurtle(screen)
p.speed(0)
def draw(event):
p.goto(event.x-256,185-event.y) #The numbers are here because otherwise the turtle draws off center. Might be different depending on computer.
canv.bind('<B1-Motion>', draw)
box.mainloop()