Hiding the turtle in python turtle drawing

Viewed 277

I am trying to make it so that the turtle is hidden from the beginning of the program but even after putting t.hideturtle() right below where I declare the turtle as variable t the turtle still seems to show up in the middle of the drawing.

import turtle
from random import randint

s = turtle.getscreen()
t = turtle.Turtle()
t.hideturtle()
rx = randint(50,100)
ry = randint(50,100)
width, height = 32,32
s.screensize(width, height)
s.bgcolor("black")

t.goto(0,0)
t.speed(15)

num=10
while num<=1000:
    r = randint(1,5)
    if r == 1:
        t.pencolor("white")
    elif r == 2:
        t.pencolor("#00FFFF")
    elif r == 3:
        t.pencolor("#89CFF0")
    elif r == 4:
        t.pencolor("#0000FF")
    elif r == 5:
        t.pencolor("#00FFFF")
    t.right(25)
    t.circle(num)
    num=num+10
    count=num//10
print("ran",count,"times")
3 Answers

This was a tricky one.

The key problem here is that your first statement creates one turtle and returns you its screen. That turtle remains visible. Your second statement creates a new turtle, which you hide. Change the order to:

t = turtle.Turtle()
s = t.getscreen()

and it all works as expected.

@TimRoberts writes:

The key problem here is that your first statement creates one turtle and returns you its screen. That turtle remains visible. Your second statement creates a new turtle, which you hide.

This is the problem with mixing turtle's object-oriented API and it's functional API. If we change the import to force just the object-oriented API, and block the functional one, we can do:

from turtle import Screen, Turtle

screen = Screen()

turtle = Turtle()
turtle.hideturtle()

or instead do:

from turtle import Screen, Turtle

turtle = Turtle()
turtle.hideturtle()

screen = Screen()

And it makes no difference. By mixing the functional API and the object-oriented API, you can easily unintentionally create the default turtle which isn't called for in this code.

I tried this line of code and it worked for me:

import turtle

turtle.hideturtle()
Related