2

我有这个用 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 新手,所以任何帮助将不胜感激:)

谢谢

4

2 回答 2

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()
于 2013-08-20T13:31:27.943 回答
0

尝试这个

from turtle import *

tim = Turtle()

my_screen = Screen()

#my_screen.exitonclick()

tim.forward(100)
my_screen.exitonclick()
于 2021-03-15T04:49:00.190 回答