Tristan Warren
Tristan Warren

Reputation: 435

How to Close Python Turtle Properly

When I run my python program from terminal it will run fine. It uses turtle to do draw an image in a while loop.

If I close the program after the while loop has finsished and then try and run it again it throws an error but if I run it again after that it works fine

Bur if I close the program whilst it is still in the while loop it will throw the error and then when I try to run it again it will run fine

My guess is that turtle is not closing properly but every way of stopping it doesn't do anything

This is the error:

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

My code:

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()

Upvotes: 0

Views: 4746

Answers (1)

furas
furas

Reputation: 143216

exitonclick() removes from memory some objects which normally turtle needs to work - so if you try to run in terminal/"Python Shell" any turlte command after exitonclick() then you get error turtle.Terminator.

exitonclick() expects that after exitonclick() Python will be closed and turtle doesn't need this object.

Maybe if you could force Python to import again turtle module then maybe it could work again (but normally Python remember imported modules and doesn't import again when you do again import turtle)


EDIT: I checked source code of turtle and it seems that you can set

  turtle.TurtleScreen._RUNNING = True

to run turtle again after exitonclick()

Try this code with and without 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

But maybe with more complex code it will not work because exitonclick() does other things - oryginal function which is executed by 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()

Upvotes: 2

Related Questions