Search code examples
pythonturtle-graphicspython-turtlepython-3.9

Turtle animation is so fast in python


I made windmill but it is moving so fast. I use turtle library to do that and t2 is only for circle, t makes the main job. I use tracer/update and I tried some numbers inside tracer but nothing changed. How can I do that animation at normal speed?

import turtle
screen = turtle.Screen()
screen.tracer(0)         
t2 = turtle.Turtle()
t2.speed(2)
t2.forward(50)
t2.setheading(90)
t2.circle(50)
t = turtle.Turtle()
t.speed(2)
def rectangle() :
    t.penup()
    t.forward(170)
    t.left(90)
    t.pendown()
    t.forward(5)
    t.left(90)
    t.forward(120)
    t.left(90)
    t.forward(10)
    t.left(90)
    t.forward(120)
    t.left(90)
    t.forward(5)
def windmill():
    for i in range(4):
        rectangle()
        t.penup()
        t.goto(0,0)
        t.pendown()
while True:
    t.clear()
    windmill()
    screen.update()
    t.left(10)

Solution

  • You can use the sleep method from the built-in time module:

    import turtle
    from time import sleep # Imported here
    
    screen = turtle.Screen()
    screen.tracer(0)         
    t2 = turtle.Turtle()
    t2.forward(50)
    t2.setheading(90)
    t2.circle(50)
    t = turtle.Turtle()
    def rectangle() :
        t.penup()
        t.forward(170)
        t.left(90)
        t.pendown()
        t.forward(5)
        t.left(90)
        t.forward(120)
        t.left(90)
        t.forward(10)
        t.left(90)
        t.forward(120)
        t.left(90)
        t.forward(5)
    def windmill():
        for i in range(4):
            rectangle()
            t.penup()
            t.goto(0,0)
            t.pendown()
    while True:
        sleep(0.05) # Used here
        t.clear()
        windmill()
        screen.update()
        t.left(10)
    

    A smoother way is to just reduce the left amount for each iteration of the while loop:

    import turtle
    
    screen = turtle.Screen()
    screen.tracer(0)         
    t2 = turtle.Turtle()
    t2.forward(50)
    t2.setheading(90)
    t2.circle(50)
    t2.speed(2)
    t = turtle.Turtle()
    t.speed(2)
    def rectangle() :
        t.penup()
        t.forward(170)
        t.left(90)
        t.pendown()
        t.forward(5)
        t.left(90)
        t.forward(120)
        t.left(90)
        t.forward(10)
        t.left(90)
        t.forward(120)
        t.left(90)
        t.forward(5)
    def windmill():
        for i in range(4):
            rectangle()
            t.penup()
            t.goto(0,0)
            t.pendown()
    while True:
        t.clear()
        windmill()
        screen.update()
        t.left(0.2) # Reduced here!