Python turtle在关闭时抛出错误

时间:2013-08-11 16:04:12

标签: python tkinter turtle-graphics

我有这个用Python 2.7.5制作的简单程序。基本上我只是在屏幕上绘制一堆随机的东西,但当我关闭画布时,我得到了一个奇怪的错误。

import turtle
import random
import time

turtle.hideturtle()

class Mus:

    def __init__(self):
        turtle.setx(random.randint(1,100))
        turtle.sety(random.randint(1,100))
        turtle.circle(random.randint(1,100))

while True:
    Mus()

turtle.exitonclick()

当我关闭程序时,我收到此错误:

Traceback (most recent call last):
  File "/Users/jurehotujec/Desktop/running.py", line 15, in <module>
    Mus()
  File "/Users/jurehotujec/Desktop/running.py", line 12, in __init__
    turtle.circle(random.randint(1,100))
  File "<string>", line 1, in circle
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/turtle.py", line 1908, in circle
    self._rotate(w)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/turtle.py", line 3110, in _rotate
    self._update()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/turtle.py", line 2564, in _update
    self._update_data()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/turtle.py", line 2555, in _update_data
    self._pencolor, self._pensize)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/turtle.py", line 569, in _drawline
    self.cv.coords(lineitem, *cl)
  File "<string>", line 1, in coords
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2240, in coords
    self.tk.call((self._w, 'coords') + args)))
TclError: invalid command name ".4335016920"

我做错了什么? 我是python的新手,所以任何帮助都会受到赞赏:)

由于

2 个答案:

答案 0 :(得分:2)

看来你的循环在Tk破坏了一些重要的对象后试图继续。您可以通过旗帜发出结束事件的信号:

import turtle
import random
import time
import Tkinter as tk



turtle.hideturtle()

closed = False
def on_close():
    global closed
    closed = True
    exit()

# Register hander for close event    
tk._default_root.protocol("WM_DELETE_WINDOW", on_close)


class Mus:

    def __init__(self):
        turtle.setx(random.randint(1,100))
        turtle.sety(random.randint(1,100))
        turtle.circle(random.randint(1,100))

# check the flag
while not closed:
    Mus()





turtle.exitonclick()

答案 1 :(得分:0)

试试这个

from turtle import *

tim = Turtle()

my_screen = Screen()

#my_screen.exitonclick()

tim.forward(100)
my_screen.exitonclick()