- Turtle - First Turtle & Coordinates
- Turtle - Forward, Backward, Angles, Directions
- Turtle - For Loop, Speed, Circle, Dot
- Turtle - Background Color, Shapesize, Pensize
- Turtle - Window Size, Bg Image, Clear Screen
- Turtle - Shape, Shape Size, Pen Color, Fill Color
- Turtle - For Loop, While Loop
- Turtle - Move Turtle with Arrow Keys
- Turtle - Move Turtle with Mouse
- Turtle - Drag Turtle with Mouse
- Turtle - Turtle Race Game
- Turtle - Automatic Winner Detection
Thursday, May 1, 2025
Python Turtle Tutorial
Monday, April 21, 2025
Python Turtle - Turtle Race - Automatic Winner Detection
This is Turtle Race Game with Automatic Winner Detection.
Run this code and than we will explain how to automatically detect winning turtle:
from turtle import *
import random
t1 = Turtle()
t1.shape("turtle")
t1.speed(0)
t1.penup()
t1.left(90)
t1.color("red")
t2 = t1.clone()
t2.color("yellow")
t1.goto(-300, -300)
t2.goto(300, -300)
#-----------------------------
finish_1 = Turtle()
finish_1.penup()
finish_1.goto(-300, 300)
finish_1.pendown()
finish_1.circle(20)
finish_1.hideturtle()
finish_2 = Turtle()
finish_2.penup()
finish_2.goto(300, 300)
finish_2.pendown()
finish_2.circle(20)
finish_2.hideturtle()
#-----------------------------
def main():
for x in range(600):
t1.fd(random.randrange(10))
#t1.shapesize(15, 15, 15)
t2.fd(random.randrange(10))
#t2.shapesize(15, 15, 15)
if (t1.position()[1]) >= 300:
print("Turtle 1 WINS")
break
elif (t2.position()[1]) >= 300:
print("Turtle 2 WINS")
break
main()
There's no need to change source for turtle creation and starting points. We will just change custom functions that deals with random movements:
def main():
for x in range(600):
t1.fd(random.randrange(10))
#t1.shapesize(15, 15, 15)
t2.fd(random.randrange(10))
#t2.shapesize(15, 15, 15)
if (t1.position()[1]) >= 300:
print("Turtle 1 WINS")
break
elif (t2.position()[1]) >= 300:
print("Turtle 2 WINS")
break
To speed things up, we are using value 10 as argument for randrange() function.
Then we are introducing if / elif check to detect when any of turtles t1 and t2 reaches position 300 verticaly. How is that done ?
When we say t1.position()[1] >= 300 that means we are checking if t1 is reaching 300 value or more on y (vertical) axis. If that is correct, t1 is winner and there is no need to check more, that's why we need to break.
If t2 reaches 300 or more vertically, same story, t2 is winner and there's break again.
Results will be printed in Python Shell.
This is end of this tutorial, and corresponding YouTube playlist.
Python Turtle - Turtle Race Game
This is source for simple turtle race game. It's not that hard to write and there is a lot of space for experimentation.
First test that you can run this code, and then we will explain:
from turtle import *
import random
#Code for Players (Turtles)
t1 = Turtle()
t1.shape("turtle")
t1.speed(0)
t1.penup()
t1.left(90)
t1.color("red")
t2 = t1.clone()
t2.color("yellow")
t1.goto(-300, -300)
t2.goto(300, -300)
#Code for Targets (also Turtle, but Circle Shape)
finish_1 = Turtle()
#finish_1.penup()
finish_1.goto(-300, 300)
#finish_1.pendown()
finish_1.circle(20)
finish_1.hideturtle()
finish_2 = Turtle()
#finish_2.penup()
finish_2.goto(300, 300)
#finish_2.pendown()
finish_2.circle(20)
finish_2.hideturtle()
#-----------------------------
def main():
for x in range(600):
t1.fd(random.randrange(3))
t1.shapesize(5, 5, 5)
t2.fd(random.randrange(3))
t2.shapesize(5, 5, 5)
main()
We have 2 turtle objects here, turtle t1 and t2. Turtle t2 is clone of turtle t1, but color is different.
Shape for object is real turtle, and starting points are same horizontaly.
Starting orientation is upwards, to the top of the screen, because thats the path turtles need to travel.
This is code for turtle t1:
t1 = Turtle()
t1.shape("turtle")
t1.speed(0)
t1.penup()
t1.left(90)
t1.color("red")
This is source for t2 which is clone of t1:
t2 = t1.clone()
t2.color("yellow")
Starting positions for both turtles:
t1.goto(-300, -300)
t2.goto(300, -300)
Target Positions
Another 2 turtles will imitate target positions that t1 and t2 must reach. When turtles finish_1 and finish_2 reach their destination they will paint circle.
Circles are place where turtles t1 and t2 must land to claim victory.
This is code for objects finish_1 and finish_2:
finish_1 = Turtle()
#finish_1.penup()
finish_1.goto(-300, 300)
#finish_1.pendown()
finish_1.circle(20)
finish_1.hideturtle()
finish_2 = Turtle()
#finish_2.penup()
finish_2.goto(300, 300)
#finish_2.pendown()
finish_2.circle(20)
finish_2.hideturtle()
You can use penup() or pendown() methods to see full paths where objects (turtles) are going.
Custom Function for Turtle Movement
def main():
for x in range(600):
t1.fd(random.randrange(3))
t1.shapesize(5, 5, 5)
t2.fd(random.randrange(3))
t2.shapesize(5, 5, 5)
With for loop we are setting turtle movement. Value 600 is enough.
Both turtles t1 and t2 will change shapesize, just for fun.
We use random module and randrange() method to get random steps for both turtles. That will imitate different speeds in specific moment of time.
So far so good. We can visually detect winner, and in next tutorial we will do that automatically.
It is important to check corresponding YouTube tutorial for Turtle Race Game.
Python Turtle - Drag Turtle with Mouse
Dragging turtle is more work than pointing turtle. We need to use new method ondrag() and pass to it same method again to try to get to new position.
This will work partially, but it's still something. At some point, app will break:
from turtle import *
t = Turtle()
t.shape("turtle")
t.shapesize(10, 10, 10)
t.speed(0)
t.color("red")
def get_coords(x, y):
t.setheading(t.towards(x, y))
t.goto(x, y)
t.ondrag(get_coords)
onscreenclick(get_coords)
To solve problem when application break, we must update our custom function by adding this line as first one:
t.ondrag(None)
So full working script is this one:
from turtle import *
t = Turtle()
t.shape("turtle")
t.shapesize(5, 5, 5)
t.color("red")
def get_coords(x, y):
t.ondrag(None)
t.setheading(t.towards(x, y))
t.goto(x, y)
t.ondrag(get_coords)
onscreenclick(get_coords)
You are strongly advised to check corresponding YouTube tutorial on How to Drag Turtle with Mouse.
Python Turtle - Move Turtle with Mouse
Moving turtle with mouse demands pointer detection. To do that we will use onscreenclick() method. As argument we will use our custom method that will print those coordinates inside Python Shell window:
from turtle import *
t = Turtle()
def get_coords(x, y):
print(x, y)
onscreenclick(get_coords)
Once we have pointer coordinates we will push turtle object to those new positions using goto() method:
from turtle import *
t = Turtle()
def get_coords(x, y):
t.goto(x, y)
onscreenclick(get_coords)
Just for fun we will change turtle object shapesize.
Also we have problem because arrow (turtle object) is always oriented to right side. Arrow will still follow mouse when we add new line inside custom function:
t.setheading(t.towards(x, y))
We are trying to set new heading to where object is oriented. But problem remains for now. This is full source:
from turtle import *
t = Turtle()
t.shapesize(10, 10, 10)
def get_coords(x, y):
t.goto(x, y)
t.setheading(t.towards(x, y))
onscreenclick(get_coords)
Solution is simple. We need to change order of lines in custom function, like this:
def get_coords(x, y):
t.setheading(t.towards(x, y))
t.goto(x, y)
Now our turtle object will rotate and travel in same direction:
from turtle import *
t = Turtle()
t.shapesize(10, 10, 10)
t.speed(0)
t.color("red")
def get_coords(x, y):
t.setheading(t.towards(x, y))
t.goto(x, y)
onscreenclick(get_coords)
You are definitely advised to check YouTube tutorial on How to move Turtle with Mouse.
Python Turtle - Move Turtle with Arrow Keys
Moving turtle object using keyboard is easy. We need 4 dedicated functions. All of them will move in specific direction for 20 pixels or degrees. We will use original turtle functions fd(), bk(), left(), right() wrapped in our own functions:
def f():
fd(20)
def b():
bk(20)
def l():
left(20)
def r():
right(20)
Having custom functions is not enough, we need to tie them with keyboard arrows:
onkey(f, "Up")
onkey(b, "Down")
onkey(r, "Right")
onkey(l, "Left")
At the end we need to listen to those keypresses using listen() method:
listen()
And this is full working script:
from turtle import *
t = Turtle()
def f():
fd(20)
def b():
bk(20)
def l():
left(20)
def r():
right(20)
onkey(f, "Up")
onkey(b, "Down")
onkey(r, "Right")
onkey(l, "Left")
listen()
This is another version where we can play around with colors, and our turtle object will automatically move when we keep arrows pressed.
We are substituting onkey() method with onkeypress() method. This is important to note.
from turtle import *
t = Turtle()
shapesize(10, 10, 10)
def f():
color("red")
fd(20)
def b():
color("blue")
bk(20)
def l():
color("green")
left(10)
def r():
color("orange")
right(10)
onkeypress(f, "Up")
onkeypress(b, "Down")
onkeypress(r, "Right")
onkeypress(l, "Left")
listen()
Definitely check YouTube tutorial on How to Move Turtle with Arrow Keys.
Python Turtle - For Loop & While Loop
Turtle for loops can provide interesting results, like circles inside circles using dedicated circle() method:
import turtle
t = turtle.Turtle()
t.speed(0)
for x in range(20, 50):
t.circle(x * 2)
Change of object orientation can be fun experiment:
import turtle
t = turtle.Turtle()
t.speed(0)
for x in range(20, 50):
t.circle(x * 2)
t.left(180)
t.circle(x * 2)
t.right(90)
And we can get same or similar results with while loops. But sometimes that demands a little bit more thinking:
import turtle
t = turtle.Turtle()
t.speed(0)
n = 20
while n < 50:
t.circle(n * 2)
t.left(180)
t.circle(n * 2)
t.left(90)
n = n + 1
Definitely check YouTube tutorial on Turtle For and While Loops.
Python Turtle - Turtle Shape, Shape Size, Pen Color, Fill Color
To set how turtle object will look, we will use shape() method. After that we can experiment with shapesize() method by passing different values as attributes:
import turtle
t = turtle.Turtle()
t.shape("arrow")
t.shapesize(10, 10, 10)
This is example when turtle object is circle:
import turtle
t = turtle.Turtle()
t.shape("circle")
t.shapesize(10, 10, 10)
This object is square:
import turtle
t = turtle.Turtle()
t.shape("square")
t.shapesize(10, 10, 10)
We can use triangle, too:
import turtle
t = turtle.Turtle()
t.shape("triangle")
t.shapesize(10, 10, 10)
And real turtle shape is created with t.shape("turtle"), if t is name of your turtle object. You can also set color for it:
import turtle
t = turtle.Turtle()
t.color("red")
t.shape("turtle")
t.shapesize(10, 10, 10)
Internal color is defined with fillcolor() method, and outside color with pencolor():
import turtle
t = turtle.Turtle()
t.fillcolor("red")
t.pencolor("yellow")
t.shape("turtle")
t.shapesize(10, 10, 10)
Animations can be done with for loops, for example:
import turtle
t = turtle.Turtle()
t.speed(1)
t.fillcolor("red")
t.pencolor("black")
t.shapesize(5, 5, 1)
for x in range(10):
t.shape("turtle")
t.left(90)
t.fd(50)
t.shape("circle")
t.fd(70)
t.shape("triangle")
t.fd(100)
t.shape("square")
Here is corresponding YouTube Tutorial for Turtle Shape, Shape Size and Pen Color.
Python Turtle - Window Size, Background Image, Clear Screen
We have multiple options to play around with window sizes. For example, to set width, height, and starting coordinates (x and y) we can use this line:
turtle.setup(800, 500, startx = 0, starty = 0)
Please note, we are talking about window here, not about individual turtle object.
To set background color and window title this source is used:
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
After that we have turtle (arrow) object creation, and for loop to create some shapes, so the full source is this one:
import turtle
turtle.setup(800, 500, startx = 0, starty = 0)
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
for x in range(4):
t.left(90)
t.pensize(5)
t.fd(50)
t.pensize(15)
t.fd(50)
t.pensize(20)
t.fd(50)
Background Image
It's easy to set background image for turtle window. Just use this line. Make note about .gif image extension:
turtle.bgpic("bg-img.gif")
And this is full working source:
import turtle
turtle.setup(800, 800, startx = 0, starty = 0)
turtle.bgpic("bg-img.gif")
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
for x in range(4):
t.left(90)
t.pensize(5)
t.fd(50)
t.pensize(15)
t.fd(50)
t.pensize(20)
t.fd(50)
Pause and Window Clear
We can have pause between operations. In this case, we are using time module and sleep() method to wait for 5 seconds before we cancel whole turtle application. Turtle window is closed with bye() method at the end of operations:
import turtle, time
turtle.setup(800, 800, startx = 0, starty = 0)
turtle.bgpic("bg-img.gif")
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
for x in range(4):
t.left(90)
t.pensize(5)
t.fd(50)
t.pensize(15)
t.fd(50)
t.pensize(20)
t.fd(50)
time.sleep(5)
turtle.bye()
To understand more, there's dedicated YouTube tutorial on Turtle Window Size, Background Image and How to Clear Turtle Screen.
Python Turtle - Background Color, Title, Shapesize, Pensize
Run this simple script, and then we will explain:
import turtle
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
t.shapesize(20, 20, 20)
To set background color we will use bgcolor() method. We are not targeting specific turtle, this method is used for turtle window:
turtle.bgcolor("lightgreen")
Same thing with turtle window title:
turtle.title("Custom Turtle Title")
We must pass 3 attributes to method shapesize() to play around with different arrow dimensions. Bu default turtle shape is arrow:
t.shapesize(20, 20, 20)
Turtle Pensize
Method pensize() is used to change size, well, pen size. Every time when we change it, we advance forward for 50 pixels:
import turtle
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
t.pensize(5)
t.fd(50)
t.pensize(10)
t.fd(50)
t.pensize(15)
t.fd(50)
t.pensize(20)
t.fd(50)
Using for loop it's easy to create interesting shapes:
import turtle
turtle.bgcolor("lightgreen")
turtle.title("Custom Turtle Title")
t = turtle.Turtle()
for x in range(4):
t.left(90)
t.pensize(5)
t.fd(50)
t.pensize(15)
t.fd(50)
t.pensize(20)
t.fd(50)
There's YouTube tutorial on turtle background color, title, shape and pensize.
Python Turtle - For Loop, Turtle Speed, Circle, Dot
We can set movement of turtles using for loops, it's easy: For every pass, a turtle will go forward for 200 pixels than turn left for 90 degrees:
import turtle
t = turtle.Turtle()
for x in range(4):
t.fd(200)
t.left(90)
There is a lot of possibilities to play around with shapes. In this one we are also using method speed(). Range for for loop is large enough to paint black ring.
A turtle (arrow, object) will go forward for 200 pixels than rotate left for 90 * 1.01. You can play around with values to get different shapes.
End turtle position is not hidden, that's why we see a small black triangle:
import turtle
t = turtle.Turtle()
t.speed(0)
for x in range(400):
t.fd(200)
t.left(90 * 1.01)
We can set color for lines and have variable pc = 1.05 set outside for loop. We are also hiding a turtle after movement is done:
import turtle
t = turtle.Turtle()
t.speed(0)
t.color("red")
pc = 1.05
for x in range(250):
t.fd(200)
t.left(90 * pc)
t.hideturtle()
It is simple to get circles inside circles. Just use higher values one after another for circle() method:
import turtle
t = turtle.Turtle()
t.circle(30)
t.circle(60)
t.circle(120)
t.circle(240)
t.hideturtle()
We can use dot() method in combination with for loop to get simple animation:
import turtle
t = turtle.Turtle()
t.speed(0)
t.color("red")
t.dot(50)
for x in range(50):
t.fd(200)
t.bk(200)
t.left(45)
t.hideturtle()
You can check corresponding YouTube tutorial on For Loop, Turtle Speed, Circle, Dot.
Python Turtle - Forward, Backward, Angles, Directions
This tutorial is all about angles and paths. It's a little bit more computational demanding because we need to think about turtle (object) rotation to reach ending point.
Make sure that this source work on you machine:
import turtle
t = turtle.Turtle()
t.left(45)
t.fd(400)
t.left(135)
t.fd(600)
t.left(90)
t.fd(600)
t.left(90)
t.fd(600)
t.left(90)
t.fd(600)
t.hideturtle()
As with last tutorial, first module import and turtle (object) creation:
import turtle
t = turtle.Turtle()
Then we are rotating a turtle for 45 degrees to the left side using left() method:
t.left(45)
Still from a centre of coordinate system we are going forward for 400 pixels, to rach point in upper right position:
t.fd(400)
When we reach it, we will rotate again to left side for 135 degrees, because we need to sent turtle in next step for 600 pixels to try to create one horizontal line, parallel to x axis:
t.left(135)
After that you can experiment with angles and paths to get box with equal sides, but this will work:
t.fd(600)
t.left(90)
t.fd(600)
t.left(90)
t.fd(600)
t.left(90)
t.fd(600)
And if there is need to hide turtle object we can always do that with hideturtle() method:
t.hideturtle()
Line / Path Colors
From last tutorial we know how to set colors for shapes.
In this case, we can use begin_fill() method to paint lines. When a specific point is reached, a turtle change colors. Please note, theres no usage of end_fill() method, because we are painting just path, not whole shape defined by a path:
import turtle
t = turtle.Turtle()
t.color("red")
t.begin_fill()
t.left(45)
t.fd(400)
t.left(135)
t.color("green")
t.fd(600)
t.color("black")
t.left(90)
t.fd(600)
t.color("magenta")
t.left(90)
t.fd(600)
t.color("navy")
t.left(90)
t.fd(600)
t.hideturtle()
You are advised to check corresponding YouTube tutorial on Turtle Methods, Angles and Directions.
Python Turtle - First Turtles & Coordinate System
This is full working source code for turtle t and z. Run this source and than we will explain:
import turtle
t = turtle.Turtle()
t.color("red")
t.begin_fill()
t.goto( 300, 300)
t.goto(-300, 300)
t.goto(-300, -300)
t.goto( 300, -300)
t.goto( 300, 300)
t.end_fill()
t.hideturtle()
z = turtle.Turtle()
z.color("yellow")
z.begin_fill()
z.goto( 200, 200)
z.goto(-200, 200)
z.goto(-200, -200)
z.goto( 200, -200)
z.goto( 200, 200)
z.end_fill()
z.hideturtle()
Creating new turtle is extremely easy, but of course, first we must import turtle module to have access to all methods.
In this simple example we will create 2 turtles, t and z. You can experiment with only one turtle t, if it's easier for you, like this:
import turtle
t = turtle.Turtle()
Then we will set color to be red using color() method:
t.color("red")
We must fill shape with that color when turtle object is done with movement. To do that begin_fill() method is used:
t.begin_fill()
In this tutorial it's all about coordinate system. Numbers you see passed to goto() functions are x and y. A turtle must travel to reach those coordinates from center of coordinate system, which is x = 0 and y = 0.
By telling t.goto(300, 300) turtle will reach upper right position and stop there waiting for next goto() command:
t.goto( 300, 300)
You can experiment a little bit, but to create red box we see in a picture, these steps are needed:
t.goto(-300, 300)
t.goto(-300, -300)
t.goto( 300, -300)
t.goto( 300, 300)
After we are done with movement, it's time to use end_fill() method, that will "finish" painting:
t.end_fill()
And if there's need to hide turtle object t, we can use hideturtle() method:
t.hideturtle()
To create z turtle (object) we will use these lines:
z = turtle.Turtle()
z.color("yellow")
z.begin_fill()
z.goto( 200, 200)
z.goto(-200, 200)
z.goto(-200, -200)
z.goto( 200, -200)
z.goto( 200, 200)
z.end_fill()
z.hideturtle()
Yellow shape created with z movement is, of course, smaller because coordinates are smaller too.
Please note, important thing here is that we are dealing with turtle coordinates, and not with angles and paths where a turtle must be pushed.
That will be a topic for next tutorial.
Tkinter Introduction - Top Widget, Method, Button
First, let's make shure that our tkinter module is working ok with simple for loop that will spawn 5 instances of blank Tk window . ...
