Python Turtle.Terminator even after using exitonclick()

Viewed 11284

I have tried to make functions for turtle to make it extremely easy to draw shapes. The code looks like this:

import turtle as t

def square():
     tw = t.Screen()
     for i in range(4):
          t.forward(100)
          t.right(90)
     tw.exitonclick()
def triangle():
     tw = t.Screen()
     for i in range(3):
          t.forward(100)
          t.right(120)
     tw.exitonclick()
def star():
     tw = t.Screen()
     for i in range(5):
          t.forward(150)
          t.right(144)
     tw.exitonclick()

When I run this code in shell a Terminator error occurs:

>>> square()
>>> triangle()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    triangle()
  File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 11, in triangle
    t.forward(100)
  File "<string>", line 5, in forward
turtle.Terminator
>>> star()
>>> square()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    square()
  File "C:\Users\Manop\Desktop\XENON\turtleg.py", line 5, in square
    t.forward(100)
  File "<string>", line 5, in forward
turtle.Terminator
>>> 

I can't understand what the problem is, because I even used exitonclick().

5 Answers

I had the same error while I was working on a school project. After some research on the turtle library I have found a variable called TurtleScreen._RUNNING, if this variable is set to True a turtle window opens, if not you get the turtle.Terminator error. Every time you close a turtle screen, TurtleScreen._RUNNING is automatically set to True, if you want to avoid that, you can simply write this line of code TurtleScreen._RUNNING = True (of course you need to import turtle before).

This is because the turtle module (most reference implementations as of today) uses a class variable called _RUNNING. This becomes false during the exitonclick() method.

Changing your code to below should help to run in the way you want:

import turtle as t

def square():
    t.TurtleScreen._RUNNING=True
    tw = t.Screen()
    for i in range(4):
        t.forward(100)
        t.right(90)
    tw.exitonclick()

def triangle():
    t.TurtleScreen._RUNNING=True
    tw = t.Screen()
    for i in range(3):
        t.forward(100)
        t.right(120)
    tw.exitonclick()

def star():
    t.TurtleScreen._RUNNING=True
    tw = t.Screen()
    for i in range(5):
        t.forward(150)
        t.right(144)
    tw.exitonclick()
Related