我有一个用 Python 2.7.5 制作的简单程序。基本上我只是在屏幕上绘制一堆随机的东西,但是当我关闭 Canvas 时我得到了一个奇怪的错误。
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 的新手,所以任何帮助将不胜感激:)
谢谢
请您参考如下方法:
似乎您的循环试图在 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()
