Introduction
Subscribe to Tech with Tim
Turtle Module
The turtle module is a builtin module in python, meaning you do not have to install it. It is used to create basic 2D shapes and drawings and is extremely beginner friendly. The main advantages of turtle is that it is extremely simple and makes it very easy to draw things to the screen. That being said the turtle module does offer support for some more advanced functionality which I will be talking about in later tutorials.
To start using the turtle module we must first import it.
import turtle
Now we have to create a turtle object that we can later move around and draw things to the screen.
import turtle tim = turtle.Turtle() # Now we can use the variables tim to reference our turtle
Once we've created our turtle object we can set some default properties for it.
import turtle tim = turtle.Turtle() tim.color("red") tim.pensize(5) tim.shape("turtle")
There are 4 basic commands that we will use to move the turtle around the screen.
- .forward(pixels)
- .backward(pixels)
- .left(angle)
- .right(angle)
import turtle tim = turtle.Turtle() tim.color("red") tim.pensize(5) tim.shape("turtle") tim.forward(100) tim.left(90) tim.forward(100) tim.left(90) tim.forward(100) tim.left(90) tim.forward(100)
This results in a square being drawn to the screen.
Another two methods that are very useful are:
- .penup()
- .pendown()
We use these methods to left the turtle pen so when we move the turtle object no line will drawn on the screen.
import turtle tim = turtle.Turtle() tim.color("red") tim.pensize(5) tim.shape("turtle") tim.forward(100) tim.left(90) tim.penup() # Lifts the pen tim.forward(100) tim.left(90) tim.pendown() # Puts the pen back down tim.forward(100) tim.left(90) tim.forward(100)
Now we can see one side of the square is not drawn.
To change the speed of the turtle we can use .speed(int).
import turtle tim = turtle.Turtle() tim.speed(5)