如何正确关闭Python龟

时间:2017-01-13 22:18:45

标签: python python-3.x turtle-graphics

当我从终端运行我的python程序时它会正常运行。它使用乌龟在while循环中绘制图像。

如果我在while循环已经完成后关闭程序,然后尝试再次运行它会抛出一个错误,但如果我再次运行它之后就可以正常运行

Bur如果我关闭程序,而它仍处于while循环中则会抛出错误,然后当我再次尝试运行时它会运行良好

我的猜测是乌龟没有正常关闭,但每一种阻止乌龟都没有做任何事情

这是错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/tristan/Documents/Python/Orbit/orbit.py", line 16, in orbit
    t.goto(xPos,yPos)
  File "<string>", line 5, in goto
turtle.Terminator

我的代码:

import turtle as t
import time
import math

def orbit(y):
    xPos = 0
    yPos = y

    while (yPos < 15) :

        t.goto(xPos,yPos)
        yPos += 1

    time.sleep(0.005)

t.exitonclick()

1 个答案:

答案 0 :(得分:0)

exitonclick()从内存中删除一些通常turtle需要工作的对象 - 所以如果你试图在终端/“Python Shell”中运行exitonclick()之后的任何turlte命令,那么你会得到错误turtle.Terminator

exitonclick()期望在exitonclick() Python关闭后turtle不需要此对象。

也许如果你可以强制Python再次导入turtle模块,那么也许它可以再次工作(但通常Python会记住导入的模块,当你再次执行import turtle时不再导入)

编辑:我检查了turtle的源代码,似乎可以设置

  turtle.TurtleScreen._RUNNING = True

turtle

之后再次运行exitonclick()

使用和不使用turtle.TurtleScreen._RUNNING = True

尝试此代码
import turtle as t

t.goto(0,50)
t.exitonclick()

t.TurtleScreen._RUNNING = True

t.goto(50,150)
t.exitonclick()

t.TurtleScreen._RUNNING = True

但也许使用更复杂的代码它将无法工作,因为exitonclick()执行其他操作 - 由exitonclick()执行的原始函数

def _destroy(self):
    root = self._root
    if root is _Screen._root:
        Turtle._pen = None
        Turtle._screen = None
        _Screen._root = None
        _Screen._canvas = None
    TurtleScreen._RUNNING = False
    root.destroy()
相关问题