Python 海龟作图的问题

最近在帮别人看一个 Python 海龟作图的问题.
遇到的第一个问题是: 代码跑起来之后,出现的窗口会死掉

pyth1

经过研究发现产生问题的原因是缺少 turtle.mainloop() 语句(莫名其妙的是教材上根本没有这句话,这简直是误人子弟啊!)

turtle.onscreenclick(draw_kaleido)
turtle.mainloop()

 

完整代码

import turtle
import random

t=turtle.Pen()
t.speed(0)
t.width(3)
turtle.bgcolor("black")
colors=["red", "green", "yellow", "blue", "orange", "purple", "magenta", "white"]

def draw_spiral (x, y,size) :
    t.penup()
    t.setpos (x, y)
    t.pendown()
    for m in range(size):
        t.forward(m)
        t.left(61)
        
def draw_kaleido(x, y):
    print(x,y)
    t.pencolor(random.choice(colors))
    size=random.randint(20, 50)
    draw_spiral(x, y,size)
    draw_spiral(-x, y,size)
    draw_spiral(-x, -y,size)
    draw_spiral(x, -y,size)
    turtle.onscreenclick(draw_kaleido)

turtle.onscreenclick(draw_kaleido)
turtle.mainloop()
但是关闭窗口之后会出现很多错误提示
 pyth2

具体如下:

TclError: invalid command name ".50609928L"
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1537, in __call__
    return self.func(*args)
  File "C:\Python27\lib\lib-tk\turtle.py", line 699, in eventfun
    fun(x, y)
  File "C:\Python27\test1.py", line 22, in draw_kaleido
    draw_spiral(x, y,size)
  File "C:\Python27\test1.py", line 15, in draw_spiral
    t.forward(m)
  File "C:\Python27\lib\lib-tk\turtle.py", line 1552, in forward
    self._go(distance)
  File "C:\Python27\lib\lib-tk\turtle.py", line 1520, in _go
    self._goto(ende)
  File "C:\Python27\lib\lib-tk\turtle.py", line 2990, in _goto
    screen._pointlist(self.currentLineItem),
  File "C:\Python27\lib\lib-tk\turtle.py", line 760, in _pointlist
    cl = self.cv.coords(item)
  File "<string>", line 1, in coords
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2295, in coords
    self.tk.call((self._w, 'coords') + args)))
TclError: invalid command name ".50609928L"

 

产生这个问题的原因,根据我的判断是:当前正在绘制图形的时候, onscreenclick 会打断这个进程从而导致问题. 有一种解决方法是在绘制的时候, 用onscreenclick(none) 阻止事件的发生. 但是很明显这样的效果不好.但是除此之外暂时没有其他办法了,

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注