Swell Python Scripts with the Turtle Library

Updated 19 April 2022

Time to flex some of the coding muscles we have gained. Using the knowledge we have with Python, this guide will go through the creation of interesting and dynamic graphic animations. The first codes in this tutorial are generators for geometric shapes. These scripts all use functionality from the Turtle Standard Library. This is pre-installed into Python by default and is a graphical library. Then the last script in this guide will generate a turtle race! Perfect for an afternoon coding session. Thus, this guide will ease you into the first steps of coding with an objective. Contents on the guide can be seen below.

There are several related tutorials on our website to help you become a coding conjurer. A great place to start would be Python Rundown and Main Windows and Python and MicroPython - Compare and Access. These will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are micro-processors that can easily fit on the palm of your hand!

As always if you have any questions, queries or things to add please let us know your thoughts!


Overview on Turtle Library

Think of the turtle library as a whiteboard with a small robot turtle situated on top of it. This robot turtle leaves a pen line behind itself whenever it moves. The size and dimensions of this pen line can be pre-decided in code. Also, the robot turtle can be controlled by code. Thus, by commanding the robot turtle to move you can draw lines all over the board. This white board is a pop-up window which is white unless otherwise specified. All of this can be seen in the image below and to the right.

A Python becoming a turtle! Also an introduction to the Python Turtle Pop-up Window

Before you can use the turtle library you have to import it to your code. The turtle library is installed in Python by default. So, to allow your code to access the functionalities you must utilise the | import | keyword. To get yourself up to speed on this keyword an excellent tutorial to check out would be Import, From and As Keywords in Python.


Geometric Patterns using Turtle Library

The scripts below will introduce the control methods for the robot turtle and different options available when utilising the turtle library. There is no end to the number of interesting patterns and geometrical shapes you can create using this method. All the scripts can be found in the Download the Codes section at the bottom of the page. For each image below the Python Programming Window is on the left and the Python Turtle Graphics Window will be on the right. All the scripts below start by importing the functionality from the turtle library. This allows the functionality to be utilised within the script. All looking pretty swell.

First script. In this the robot turtle will draw a square as it follows our code commands seen below. This square is created in the turtle pop-up window and the code written in the Python Programming Window which you can see below. 

Square made in the Python Turtle Pop-up Window

 

Second Script. In this the robot turtle will draw us an octagon as it follows the coded commands seen below. This is seen below with the Python Turtle Graphics Window on the right and the code written in the Python Programming Window on the left. This script demonstrates how easy it is to utilise loops to command the robot turtle.

Octagon made in the Python Turtle Pop-up Window

 

Third Script. In this an interesting shape will be created by the robot turtle forever so long as the code is executing seen below. This is because the code commanding the robot turtle to move is a part of an infinite loop. This script is really getting that robot turtle to work. This code demonstrates that there is no limit to the amount of commands you can give to the robot turtle.

Interesting shape made in the Python Turtle Pop-up Window

 

Fourth Script. In this a star shape will be created by the robot turtle as it follows the coded commands seen below. Once completed the enclosed areas of the star shape will be filled in with a yellow colour. Another infinite loop is created below with a break statement enclosed used to end the loop. This break statement is triggered in the code by an if statement which will stop the robot turtle once it has returned to the starting position. 

Star made in the Python Turtle Pop-up Window


Coding a Turtle Race

Code for the Turtle race is below. It has been extensively commented with depth to explain the inner workings. Copy and paste it into your Python Programming Window, write it out or download the code from the bottom section and open it using the Python IDLE Shell. Either way it will run on any default install of Python. The first few lines of code are importing all the particular functionality that comes pre-installed with Python to the script.

#As it is traditional to do so all the extra functionality desired for this turtle race is imported at the start.
#All the particular functionality utilised will comes pre-installed on a default installation of Python.
import time
import turtle
from turtle import Turtle
from random import randint

#Setting up the pop-up window! And placing the title words in the centre top of the Python Turtle Graphics Window
#The function turtle.penup() effectively is lifting the robot turtle off the page and moving it, thus no pen line
window = turtle.Screen()
window.title("Turtle Racing Occuring in this Pop-Up Window!")
turtle.bgcolor("Green")
turtle.color("White")
turtle.speed(0)
turtle.penup()
turtle.setpos(-420, 260)
turtle.write("Come one, Come all! It is Turtle Racing Time!", font=("Arial", 30, "bold"))
turtle.penup()

#Adding some dirt to the base, This is similar to the star example above using the turtle.begin_fill() and is similar to drawing with a CNC machine.
#The starting point is decided on, the turtle is put onto the page and then movement commands are given to the robot turtle. 
turtle.setpos(-280, 225)
turtle.color('Brown')
turtle.begin_fill()
turtle.pendown()
turtle.forward(520)
turtle.right(90)
turtle.forward(445)
turtle.right(90)
turtle.forward(520)
turtle.right(90)
turtle.forward(445)
turtle.end_fill()

#Create a finishing line! Every turtle race needs one
#This used the turtle.stamp() functionality which when set like below lets you stamp white squares  
stamp_size = 20
square_size = 15.5
finish_line = 180

turtle.color('white')
turtle.shape('square')
turtle.shapesize(square_size / stamp_size)
turtle.penup()

#Now to make the finish line look checkered! It uses two loops to fill fourteen white stamp sections of colour

for i in range(14):
    turtle.setpos(finish_line, (211 - (i * square_size * 2)))
    turtle.stamp()

for j in range(14):
    turtle.setpos(finish_line   square_size, ((211 - square_size) - (j * square_size * 2)))
    turtle.stamp()

#And with all the above the field is now set!
#Now it is time to get our robot turtle competitors ready!
#Robot Turtle Number One, aka Franklin. Think of below as the stat blocks for the starting location and colour of turtles.

turtle1 = Turtle()
turtle1.speed(0)
turtle1.color("Black")
turtle1.shape("turtle")
turtle1.penup()
turtle1.goto(-275, 140)
turtle1.pendown()

#Turtle Number Two, aka Sonik (possibly a hedgehog in disguise)

turtle2 = Turtle()
turtle2.speed(0)
turtle2.color("Yellow")
turtle2.shape("turtle")
turtle2.penup()
turtle2.goto(-275, 60)
turtle2.pendown()

#Turtle Number Three, aka Michelangelo

turtle3 = Turtle()
turtle3.speed(0)
turtle3.color("lightblue")
turtle3.shape("turtle")
turtle3.penup()
turtle3.goto(-275, -20)
turtle3.pendown()

#Turtle Number Four, aka Crush

turtle4 = Turtle()
turtle4.speed(0)
turtle4.color("Orange")
turtle4.shape("turtle")
turtle4.penup()
turtle4.goto(-275, -110)
turtle4.pendown()

#And with that our competitors are on the Field!

#Pauses the game for three seconds so that all the turtles and all the bets can be wagered ready for the race!
time.sleep(3)

#This loop decides the end of the race. The end of the race happens once i reaches 145 iterations.  
#Most races will be over by this point. Movement speed of the turtles is also decided here
#If you wanted to program in an unfair advantage this is the spot to do it. 

for i in range(145):
    turtle1.forward(randint(1,5))
    turtle2.forward(randint(1,5))
    turtle3.forward(randint(1,5))
    turtle4.forward(randint(1,5))

#Finally a simple and easy way to get out of window is coded in below. By clicking anywhere on the window
#You can exit the application

turtle.exitonclick()

Time for a Turtle Race!

Roll up and be ready! It is time for some racing to go down using the Python script we made above. Copy the above script into the Python Programming Window, write it all out there or download the code at the bottom of the page and open it up with the Python IDLE Shell to get started. By utilising the turtle, time and random libraries that are built into Python by default we can get some serious turtle races into gear. Check out all the swell action in an epic race caught with multiple screen captures seen below. As you can see there was a close victory by the turtle in yellow today! 

Progression of a Turtle Race


THE NEXT STEP

The natural next step in our coding adventures would using API in our codes. The best place to jump into the world would be the guide Cool API Python Scripts. This lets us start touching the wide world of Internet of Things and break your codes free from the constraints of the digital landscape and let them start affecting the real, breathing, physical outside world. Learning API will allow the happenstances of the natural world to become decisions inside code which can then in turn make choices in the real world.


DOWNLOAD THE CODES

Below you can find all the code for the above examples. You will be able to run the codes here on your own computing device and modify the code at your leisure. Open the scripts with Python IDLE Shell and run them using the Python Programming Window.

Attachment - Swell-Scripts-with-Turtle-Library.zip

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.