Magal
Magal

Reputation: 3

Python turtle error on closing screen - code from How to Think Like a Computer Scientist: Learning with Python 3

when I run this code

import turtle
import time

def show_poly():
    try:
        win = turtle.Screen()
        tess = turtle.Turtle()
        n = int(input("How many sides do you want in your polygon?"))
        angle = 360 / n
        for i in range(n):
            tess.forward(10)
            tess.left(angle)
        time.sleep(3)
    finally:
        win.bye()

show_poly()
show_poly()
show_poly()

I get the first call work properly than I get this error

Traceback (most recent call last): File "/home/turte.py", line 19, in show_poly()

File "/home/turte.py", line 8, in show_poly tess = turtle.Turtle()

File "/usr/lib/python3.5/turtle.py", line 3816, in init visible=visible)

File "/usr/lib/python3.5/turtle.py", line 2557, in init self._update()

File "/usr/lib/python3.5/turtle.py", line 2660, in _update self._update_data()

File "/usr/lib/python3.5/turtle.py", line 2646, in _update_data self.screen._incrementudc()

File "/usr/lib/python3.5/turtle.py", line 1292, in _incrementudc

raise Terminator turtle.Terminator

If I understand the problem I cannot create a new screen even if I closed the last. I run python 3.5

Upvotes: 0

Views: 1541

Answers (2)

cdlane
cdlane

Reputation: 41925

Another approach is to work within turtle and avoid tkinter when possible. In the following solution, instead of destroying the window and making a new one, we simply clear it and draw anew:

from turtle import Turtle, Screen
from time import sleep

def show_poly(turtle):
    n = 0

    while n < 3:
        try:
            n = int(input("How many sides do you want in your polygon? "))
        except ValueError:
            pass

    angle = 360 / n

    for _ in range(n):
        turtle.forward(50)
        turtle.left(angle)

    sleep(3)
    turtle.clear()

window = Screen()

tess = Turtle()

show_poly(tess)
show_poly(tess)
show_poly(tess)

window.bye()

This should also be compatible with both Python 2.7 and Python 3

Upvotes: 0

Stop harming Monica
Stop harming Monica

Reputation: 12618

The object returned by turtle.Screen() is intended to be a singleton so your code is actively fighting the module design. Accourding to the docs you should be using an instance of RawTurtle in applications.

import turtle
import time
import tkinter as tk


def show_poly():
    try:
        n = int(input("How many sides do you want in your polygon?"))
        angle = 360 / n
        root = tk.Tk()
        canvas = turtle.ScrolledCanvas(root)
        canvas.pack(expand=True, fill='both')
        tess = turtle.RawTurtle(canvas)
        for i in range(n):
            tess.forward(10)
            tess.left(angle)
        time.sleep(3)
    finally:
        root.destroy()


show_poly()
show_poly()
show_poly()

Upvotes: 1

Related Questions