Set delay in drawing in Python Turtle

In this tutorial, we will learn how to set a delay in drawing in Python Turtle.

Python becomes even more interesting when it comes to exploring graphics. This is because Python has many built-in modules that possess a strong capability to process graphics, while also supporting various third-party graphic processing libraries. One such library is the Turtle which enables us to work with digital art and animations.

Python Turtle Library

Turtle is a fun and easy way to create graphics while programming. The turtle moves like a pen on the screen and draws the output in real-time, providing instant feedback. Since Turtle is a built-in library, no pre-installation is needed. To get started, simply import the turtle library.

import turtle

Now, let us implement the delay method.

Set delay in drawing in Python Turtle

The delay is an animation control method that returns or sets the delay of the animation in milliseconds. We can use this method to set the time interval between two successive motions. The animation speed will be slower with a longer delay. For official documentation, refer here.

Syntax

screen.delay()

To set a delay, we can pass a positive integer as a parameter. If no value is passed, the delay function will simply return the current delay.

Let us code a simple example.

Example

In this example, we will be creating a spiral. After each spiral curve step, we will increment the delay which will impact the speed of the animation. Additionally, we will display the delay on each increment for better understanding.

import turtle

#Create objects
spiral = turtle.Turtle()
t = turtle.Turtle()

for i in range(70):
    #Draw the animation
    spiral.forward(5+i)
    spiral.right(15)

    #Set the delay
    spiral.screen.delay(10+i)

    #Return the current delay
    t.clear()
    t.write("Delay= " + str(spiral.screen.delay()), font=('Arial', 15, 'normal'))

turtle.done()

Here, we have created two turtle objects. The first one draws the spiral and we have set and updated the delay on it. The second one returns the updated delay each time. We took the help of turtle clear and write methods to display the delay. The final result looks like this-

Output

(gif format)

Set delay in drawing in Python Turtle

You can notice a delay of 1 millisecond with each curve step. Simple, isn’t it? You can now experiment with the delay method with more complex animations. Happy Learning!

Leave a Reply

Your email address will not be published. Required fields are marked *