100% found this document useful (2 votes)
1K views

Python Turtle Graphics The Complete Guide

The document discusses Python turtle graphics and provides code examples to: 1) Create a turtle window and change the background color. 2) Change the color of the turtle and set its heading direction. 3) Draw lines using turtle.fd() and turtle.goto() methods and change the thickness of lines. 4) Hide the turtle arrowhead to draw lines without seeing the turtle. The document concludes by proposing a project to draw a square using turtle graphics.

Uploaded by

Carlos Guerrero
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
1K views

Python Turtle Graphics The Complete Guide

The document discusses Python turtle graphics and provides code examples to: 1) Create a turtle window and change the background color. 2) Change the color of the turtle and set its heading direction. 3) Draw lines using turtle.fd() and turtle.goto() methods and change the thickness of lines. 4) Hide the turtle arrowhead to draw lines without seeing the turtle. The document concludes by proposing a project to draw a square using turtle graphics.

Uploaded by

Carlos Guerrero
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Python Turtle Graphics – The Complete Guide.

coolpythoncodes.com /python-turtle/

by Rapture Godson 7/30/2017

Python turtle graphics is one of the cool ways to implement your knowledge in Python before you start writing
complex programs to solve problems in life.

In this tutorial, I will make Python more practical for you and also fun.

I know that before you came across this tutorial, you were looking for fun things to do with Python.

So I will do my best to make every bit of this tutorial exciting.

let’s get to the basics now.

Don’t forget to:

How to Create a Turtle Window.


To create a turtle window on your computer screen, please open a new file editor window and type the following
code snippet. Save it as Turtle_window.py

Python turtle window


Python

1 from turtle import Turtle


2 t=Turtle()

When you run this program, you will get this result on your screen.

1/47
Python Turtle Graphics Window

You can see an arrow head at the middle point of the window pointing to the east which is the default position. This
location is called home.

The position of the turtle is specified with the two-dimensional coordinate system, (x,y).

The default position of the turtle(arrow head) is (0,0) which is the center of the window.

I will have to talk about some things that are important and it is for those that will use Python IDE (pycharm, spyder
etc) for this tutorial.

When you run the code snippets of this tutorial in any Python IDE you will notice that the turtle window will open and
close immediately.

To allow the turtle window stay so you can see the output of your program, include t.screen.mainloop() in your
program. It should be the last statement of your program.

To make the turtle window disappear after viewing the turtle screen when you click on the turtle canvas, use the
method screen.exitonclick() .

Include t.screen.exitonclick() before t.screen.mainloop().

2/47
The following code snippet shows you how you can use them.

For Python IDE users


Python

1 from turtle import Turtle


2
3 t=Turtle()
4
5 t.screen.exitonclick()
6
7 t.screen.mainloop()

When you run the code snippet above in any Python IDE such as Pycharm or Spyder, the turtle screen won’t
disappear immediately unless you click on the turtle canvas.

How to Change the Turtle Window Background Color


The default background color is white which can be boring.

To change the color of the turtle window background, please open a new file editor window and type the following
code snippet. Save it as Turtle_window_background.py

Python Turtle Graphics Window


Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor('black')

When you run this program, you will get this result on your screen.

3/47
Python Turtle Graphics Window

The background color of the turtle window is black but there is no turtle because the default color of the turtle is
black.

Note :

The screen.bgcolor() method accepts one argument which is the color of the turtle window as a string.

The default color of Python turtle window is white. You can change it using the method screen.bgcolor()

How to Change the Color of the Turtle


To change the color of the turtle,

Type the following code snippet into a new file editor and save it as any name you like.

Python

4/47
1 from turtle import Turtle
2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("blue")

When you run this program, you will get this result on your screen.

Blue turtle on a black canvas

t.color(“blue”) changes the color of the turtle to blue.

How to change the Background picture of the Turtle Screen.


Here’s a code snippet that changes the background image of the turtle screen( turtle_background_pic.py) .

How to change the turtle background image


Python

5/47
1 from turtle import Turtle
2
3 t=Turtle()
4
5 t.hideturtle()
6
7 t.screen.bgpic("night-owl-75.gif")

Here’s the output of the program(turtle_background_pic.py)

An Owl image on turtle canvas

Note:

Only the gif image format is accepted.


Let your program and the gif image be in the same folder on your computer.
I provided some gif images in the source code download file.

How to Set the Heading of the Turtle


6/47
By default the turtle faces the east, to change the direction in which the turtle is facing,

Set turtle heading


Python

1 from turtle import Turtle


2 t=Turtle()
3 t.setheading(180)

The syntax is,

t.setheading(angle)

Angle 90 sets the turtle to face the North.

Angle 180 sets the turtle to face the West.

Angle 270 sets the turtle to face the South.

Angle 360 or 0 set turtle to face the East

You can set the turtle to face any angle of your choice.

You can change the direction of the turtle using the following syntax

t.left(angle)

t.right(angle)

The above is used to rotate the turtle either to the left or to the right at the angle specified.

How to Change the Turtle Shape


The default shape of a turtle is known as a classic.

To change the shape of the turtle you use the shape() method.

The shape() method accepts a string as an argument. The string is the name of a valid shape in the TurtleScreen’s
shape dictionary.

The valid turtle shapes are:

Arrow
Circle
Square
Triangle
Turtle
Classic

Like I said earlier, the default shape of the turtle is known as a classic.

I will show you my favorite turtle shape which you will love as well.

7/47
Open a new file editor window and type the following code snippet. Save it as turtle_shape.py

turtle shape
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.shape("turtle")

when you run the program above, you will get:

Turtle Shape-“Turtle”

From the above screenshot, the turtle is small. To increase the size of the turtle, use the shapesize() method.

To illustrate this, run the following code snippet.

Turtle shape of big shape size

8/47
1 from turtle import Turtle
2 t=Turtle()
3 t.shape("turtle")
4 t.shapesize(20)

Here is the output of the above program.

Turtle shape with a bigger shape size

How to Draw a Line


To draw a line use the syntax below

t.fd(distance)

or

t.goto(x,y)

distance is the value of the length of the line.

t.goto(x,y) moves the turtle to an absolute position

Note:

The Cartesian system is the coordinate system for Turtle. So x and y represent values in the x and y axis
respectively.

t.fd(distance) moves the turtle by the specified distance.

Open a new file editor window and type the following code snippet. Save it as draw_line.py

Draw a line
Python
9/47
1 from turtle import Turtle
2 t=Turtle()
3 t.fd(100)

When you run the program above you will get:

A line with a distance of 100 pixels

The above program moves the turtle 100 pixels to the east.

Open a new file editor window and type the following code snippet. Save it as turtle_go_to.py

turtle go to

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("blue")
5 t.goto(100,50)

Running turtle_go_to.py you would get,


10/47
Drawing a line with the method goto()

How to Increase the Thickness of a Line


t.pensize() accepts an integer as an argument to set the thickness of the line.

Open a new file editor and save the following code snippet as turtle_line_thickness.py

from turtle import Turtle

increasing line thickness


Python

1 t=Turtle()
2 t.screen.bgcolor("black")
3 t.color("blue")
4 t.pensize(10)
5 t.fd(100)

when you run the code snippet above, you will get:

11/47
How to Hide the Turtle(Arrow Head)
You may not need the turtle to appear in your drawing as you just need a line. To achieve this open a new file editor
and save the following code snippet as draw_line_without_turtle.py

Hiding turtle
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.fd(100)
4 t.hideturtle()

Running this program will give you,

How to make turtle disappear

You have learned a lot, so let us do something fun with Python.

Project 1:
Write a program to draw a square on the computer screen and save it as turtle_square.py
12/47
Let the background screen color be black and color of the line drawn red.

Solution 1: for a beginner that doesn’t know Python function and for loop

Drawing a Square
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.hideturtle()
6 t.fd(100)
7 t.left(90)
8 t.fd(100)
9 t.left(90)
10 t.fd(100)
11 t.left(90)
12 t.fd(100)

The above program first changes the window background to black and the turtle to red using
t.screen.bgcolor(“black”) and t.color(“red”).

The turtle is then made invisible using this line of code t.hideturtle()

The turtle moves 100 pixels to the east (t.fd(100)) and draws a horizontal line.

It then faces the north by rotating 90degrees(t.left(90)) to the left and moves 100 pixels to the north, drawing a
vertical line.

t.left(90) makes the turtle face the west by rotating it 90 degrees left. It then moves 100 pixels to the west, drawing
a horizontal line.

t.left(90) makes the turtle face the south by rotating it 90 degrees left. It then moves 100 pixels to the south, drawing
a vertical line.

The turtle turns 90 degrees left to face the east, it then moves 100 pixels to the east which is the default position of
the turtle.

Finally, a square is drawn.

Solution 2:

Let’s make our code more readable and maintainable with function and a for loop. Save this as turtle_square1.py

Drawing a square with function and for loop


Python

13/47
1 from turtle import Turtle
2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.hideturtle()
6
7 def square(length):
8 for steps in range(4):
9 t.fd(length)
10 t.left(90)
11
12 square(100)

Running turtle_square1.py, you will get a square on your computer screen.

A square

Note:

Basically, the for loop runs through the code below four times.

t.fd(length)
14/47
t.left(90)

Did you ever do an isometric or auxiliary drawing?

Well, I did and to be honest with you, it was boring to me.

But Python made it fun as I could write some bunch of codes and my computer would do the drawing.

In the next project, you will draw an isometric block.

Project 2:
Write a program to draw a rectangle inclined to 30 degrees on the computer screen and save it as
turtle_rectangle.py

Let the screen background color be black and color of the line drawn red.

Solution 1: for a beginner that doesn’t know Python function and for loop

Inclined Rectangle
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red","blue")
5 t.left(30)
6 t.hideturtle()
7 t.fd(100)
8 t.left(90)
9 t.fd(200)
10 t.left(90)
11 t.fd(100)
12 t.left(90)
13 t.fd(200)

Solution 2:

Open a new file editor window and type the following code snippet. Save it as turtle_rectangle1.py

Inclined Rectangle
Python

15/47
1 from turtle import Turtle
2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.hideturtle()
5 t.color("red")
6
7 def slanted_rectangle(length,width,angle):
8 t.setheading(angle)
9 for steps in range(2):
10 t.fd(width)
11 t.left(90)
12 t.fd(length)
13 t.left(90)
14
15 slanted_rectangle(length=200,angle=45,width=100)

Running program turtle_rectangle.py and turtle_rectangle2.py you would get

An Inclined Rectangle

Can we do one more project?

16/47
Yes, of course.

Project 3:

Write a program to draw a triangle on the computer screen and save it as turtle_triangle.py

Let the screen background color be black and color of the line drawn red.

Solution:

Draw a Triangle
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.hideturtle()
6
7 def triangle(length,angle=120):
8 for steps in range(3):
9 t.fd(length)
10 t.left(angle)
11
12 triangle(200)

Running the above program you would get

Don’t be over excited yet, there’s a ton of room for improvement in our programs.

How to Draw a Circle


The circle() method is used to draw a circle and it can accept three arguments which are:

1. radius
2. extent
3. steps

The most important is radius and extent. Though, extent and steps are optional(i.e a circle can still be drawn without
including them.)

The radius accepts an integer which is the radius of the circle.

The extent accepts an integer which is an angle. To cut short the technical explanation, it determines the part of the
circle that will be drawn.

If you assign 360, a full circle will be drawn, 180 will draw a semi-circle. (Do you now understand why I said extent
represents an angle?)

Let’s do some coding. The code snippet below will draw a semi-circle.

Open a new file editor window and type the following code snippet. Save it as turtle_semi_circle.py

Semi circle
17/47
Python

1 from turtle import Turtle


2
3 t=Turtle()
4
5 t.circle(50,180)
6
7 t.hideturtle()

Here’s the output of the code snippet.

Semi circle

Well, let’s do something a bit harder so you can learn more.

Can you do something like this?

18/47
Semi Circle

If you could not do it, don’t worry.

Open a new file editor window and type the following code snippet. Save it as semi_circle1.py

Python

1 from turtle import Turtle


2
3 t=Turtle()
4
5 t.hideturtle()
6
7 t.up()
8
9 t.setx(50)
10
11 t.down()
12
13 t.setheading(90)
14
15 t.circle(50,180)

19/47
The only thing strange about this code snippet is t.setx().

The method setx() positions the turtle on the x-axis leaving the y-axis unchanged.

In addition, the method sety() positions the turtle on the y-axis leaving the x-axis unchanged.

In the next section, we will draw a full circle.

How to Raise Up the Turtle off the Drawing Surface


Imagine the turtle as a paint brush in the hand of an artist. The artist can lift up the brush off the canvas to place it on
another position on the canvas.

To do a similar action with the turtle, you use this syntax below,

t.up()

To put back the turtle on the canvas, use this syntax below,

t.down()

Note:

No drawing is done when the turtle is up.

Drawing is done when the turtle is down.

Let me explain the following syntax by writing cool programs

up()
down()
goto(x,y)
circle(radius)

I want you to observe the following code snippet and the diagram.

Code snippet 1:

Open a new file editor window and type the following code snippet. Save it as code_snippet_1.py

Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.goto(100,50)
6 t.circle(50)
7 t.hideturtle()

If you run the code above you will get;

20/47
code snippet 1 screenshot

From the diagram above you can observe that the turtle moved to an absolute position ( t.goto(100,50))

and a circle with a radius of 50 is drawn( t.circle(50))

The next code snippet will remove the line in the diagram above.

Code snippet 2:

Open a new file editor window and type the following code snippet. Save it as code_snippet_2.py

Python

21/47
1 from turtle import Turtle
2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.up()
6 t.goto(100,50)
7 t.down()
8 t.circle(50)
9 t.hideturtle()

If you run the code above you will get;

code snippet 2 screenshot

t.up() – raises the turtle up and no drawing is done when the turtle is up.

t.goto(100,50) – moves the turtle to an absolute position.

t.down() – brings down the turtle.

t.circle(50) – draws a circle with a radius of the value 50


22/47
You can replace t.up(), t.goto(100,50), t.down(), t.circle(50) with the method setposition()

The setposition() method accepts two arguments which are the coordinates x and y.

This method moves the turtle to an absolute position. If the turtle pen is down, a line will be drawn to the specified
position.

How to Add colors in Your Drawing


We have been drawing many shapes but we have not applied colors to our drawing.

Here are some ways to apply colors to your drawing.

t.begin_fill() and t.end_fill() –

t.begin_fill() is called before drawing a shape to be filled with the color of the turtle.

t.end_fill() fills the shape drawn with the color of the turtle after t.begin_fill() has been called.

Open a new file editor window and type the following code snippet. Save it as red_circle.py

red circle
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("red")
5 t.begin_fill()
6 t.circle(50)
7 t.end_fill()
8 t.hideturtle()

If you run the code above you will get:

23/47
Red circle

t.fillcolor()

This meth0d changes the color of the turtle only, when the turtle moves, the color path remains the default color
(black) .

The color can be passed as a string such as:

t.fillcolor(“blue”)

The next thing we are going to do will blow your mind.

Random Walk with Turtle


Open a new file editor window and type the following code snippet. Save it as turtle_random_walk.py

turtle drawing randomly


Python

24/47
1 from turtle import Turtle
2 import random
3
4 t=Turtle()
5 t.screen.bgcolor("black")
6
7 def random_drawing(turns,distance):
8 for x in range(turns):
9 right=t.right(random.randint(0,360))
10 left=t.left(random.randint(0,360))
11 t.color(random.choice(["blue","red","green"]))
12 random.choice([right,left])
13 t.fd(distance)
14
15
16
17 random_drawing(100,50)

My output of the program is:

Random drawing

Note:

We can’t get the same result.

Why?

This is because I use the random module.

A random module picks random element in a sequence.

How to Increase the Speed of the Turtle


25/47
Imagine how long it will take for your turtle to draw something like this:

Random drawing

It would take you a lot of time.

But here’s the best part of turtle,

You can increase the speed of the turtle.

How then?

t.speed() accepts an integer as an argument to set the speed of the turtle. The value 0(zero) is the fastest speed of
the turtle

So to increase the speed of the program (turtle_random_walk.py) include t.speed(0) before defining the function
randomwalk.

How to draw a dot


The dot() method receives two optional arguments, which are:

The size of a dot


The color of the dot

Here is a simple dot of size 20 and blue in color.

26/47
A dot

Here is the code snippet.

Python turtle code snippet to draw a dot


Python

1 from turtle import Turtle


2 t = Turtle()
3 t.screen.bgcolor("black")
4 t.hideturtle()
5 t.dot(20,"blue")

So we have been drawing shapes on our computer screen, and am getting really bored of it.

Let’s do something a bit different by writing text on the computer screen.

How to Write Text with Python Turtle


To write on your computer screen, use the write() method.

The write() method accepts four arguments, which are:


27/47
arg– this is the string object of the text you want to write to the TurtleScreen.
move– this argument is optional and it can only be assigned to the value “True” or “False”. When True a line
will be drawn below the text.
align– you assign this argument either to the left, right or center. This argument is also optional
font– this argument basically determines the font name, font size, font type of your text.

To understand this better, let’s write some codes.

Project 4:

Write a program to display Cool Python Codes on the turtle screen.

Open a new file editor and save the following code snippet as write_program.py

Python turtle code snippet to write on your computer screen.


Python

1 from turtle import Turtle


2 t = Turtle()
3 t.hideturtle()
4 t.write("Cool Python Codes",move=True,align="center",font=("Freestyle Script",50,"normal"))

Here is the output of the program.

28/47
Cool Python Codes

The cool font I used is “Freestyle Script” and I got it from Microsoft word application.

Let’s do something fun in Python.

I want to do some logo designs for my blog, and I don’t want to use Photoshop.

Guess what?

I will do it in Python.

Project 5: How to do logo design with Python

Here are some code snippets to the logo design for my blog.

Logo design 1:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo1.py

logo snippet 1
Python

29/47
1 from turtle import Turtle
2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("white")
5
6 def square(length):
7 for steps in range(4):
8 t.fd(length)
9 t.left(90)
10
11 def draw_square(x,y,length):
12 t.hideturtle()
13 t.up()
14 t.goto(x,y)
15 t.down()
16 t.begin_fill()
17 square(length)
18 t.end_fill()
19
20 def rectangle(length,width):
21 for steps in range(2):
22 t.fd(width)
23 t.left(90)
24 t.fd(length)
25 t.left(90)
26
27 def draw_rectangle(length,width,x,y):
28 t.hideturtle()
29 t.up()
30 t.goto(x,y)
31 t.down()
32 t.begin_fill()
33 rectangle(length,width)
34 t.end_fill()
35
36 t.write("Cool Python Codes", move=True, align='center',
37 font=('Cambria', 18, 'normal'))
38
39 draw_square(-120,-20,20)
40 draw_square(-120,30,20)
41 draw_square(-140,0,20)

Here is the output of the program above.

30/47
Code Python Codes logo design 1.

Logo design 2:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo_2.py

Logo design code snippet 2


Python

31/47
1 from turtle import Turtle
2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 t.color("blue")
6
7 def square(length):
8 for steps in range(4):
9 t.fd(length)
10 t.left(90)
11
12 def draw_square(x,y,length):
13 t.hideturtle()
14 t.up()
15 t.goto(x,y)
16 t.down()
17 t.begin_fill()
18 square(length)
19 t.end_fill()
20
21 def rectangle(length,width):
22 for steps in range(2):
23 t.fd(width)
24 t.left(90)
25 t.fd(length)
26 t.left(90)
27
28 def draw_rectangle(length,width,x,y):
29 t.hideturtle()
30 t.up()
31 t.goto(x,y)
32 t.down()
33 t.begin_fill()
34 rectangle(length,width)
35 t.end_fill()
36
37
38
39 t.write("Cool Python Codes", move=True,
40 align='center',
41 font=('Cambria',18, 'normal'))
42
43 draw_square(-120,-20,20)
44 draw_square(-120,30,20)
45 draw_rectangle(30,10,-130,0)

Here is the output of the program above.

32/47
Cool Python Codes logo design 2

Logo design 3:

Open a new file editor and save the following code snippet as Cool_Python_Codes_Logo_3.py

Logo design code snippet 3


Python

33/47
1 from turtle import Turtle
2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 t.color("magenta")
6
7 def square(length):
8 for steps in range(4):
9 t.fd(length)
10 t.left(90)
11
12 def draw_square(x,y,length):
13 t.hideturtle()
14 t.up()
15 t.goto(x,y)
16 t.down()
17 t.begin_fill()
18 square(length)
19 t.end_fill()
20
21 def rectangle(length,width):
22 for steps in range(2):
23 t.fd(width)
24 t.left(90)
25 t.fd(length)
26 t.left(90)
27
28 def draw_rectangle(length,width,x,y):
29 t.hideturtle()
30 t.up()
31 t.goto(x,y)
32 t.down()
33 t.begin_fill()
34 rectangle(length,width)
35 t.end_fill()
36
37 t.write("Cool Python Codes", move=True, align='center',
38 font=('Cambria', 18, 'normal'))
39
40 draw_square(-120,-20,20)
41 draw_square(-120,30,20)
42 draw_rectangle(30,40,-140,0)
43 draw_rectangle(70,10,-170,-20)
44 draw_rectangle(10,70,-170,-30)
45 draw_rectangle(10,70,-170,50)

Here is the output of the program above.

34/47
Cool Python Codes logo design 3

The logo below was designed using Photoshop by Tutorial Graphics.

35/47
Cool Python Codes logo

Can this tutorial get more exciting?

Yes, it can.

Let’s write programs to respond to user’s mouse clicks.

onclick() method

This method calls a function whenever the mouse is used to click on a particular coordinate.

It accepts three arguments which are:

fun– this is a function with two arguments, to which will be assigned the coordinates(x,y) of the clicked point
on the canvas.
btn– this argument is assigned to one by default, which means you click the left mouse button to call a
function. If you assign it to two, you will have to click both the left and right mouse button simultaneously to
call a function.
add– True or False. If True, a new binding will be added, otherwise, it will replace a former binding.

I usually use one argument which is the function I want to call when I click my mouse.

Here is a program that draws a circle when you click on the turtle. Save the code snippet as
click_to_draw_circle.py

Draw a circle with a mouse click


36/47
Python

1 from turtle import Turtle


2 t=Turtle()
3 t.screen.bgcolor("black")
4 t.color("orange")
5
6 def circle(x,y):
7 t.circle(60)
8
9 t.onclick(circle)

Note:

The function name “circle” has two arguments, x and y which are the coordinates you will have to click to draw a
circle.

ondrag() method

This method is basically used when you what to click on the turtle and move it. It accepts three arguments like the
onclick() method.

Here is a program to illustrate the ondrag() method.

The code snippet below is saved as turtle_ondrag.py.

Python

1 from turtle import Turtle


2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 t.color("blue")
6
7 def goto(x,y):
8 t.goto(x,y)
9
10 t.ondrag(goto)

Here’s what I drew using the program above.

37/47
I drew a cup.

onrelease() method

This method is also similar to onclick and ondrag method. To understand what this method does,

I wrote a program to draw a circle when you left click on the turtle and when you remove your hand from the mouse,
the circle will disappear.

Here is the code snippet and it is saved as turtle_onrelease.py

1 from turtle import Turtle


2
3 t=Turtle()
4
5 def draw_circle(x,y):
6 t.circle(50)
7
8 def erase_drawing(x,y):
9 t.clear()
10
11 t.onclick(draw_circle)
12 t.onrelease(erase_drawing)

38/47
Note:

You have to leave your hand on the left-hand button of the mouse until the circle is drawn on the screen.

When the circle has been drawn, you can then remove your hand from your mouse. Once you remove your hand
from the mouse, the circle disappears.

This circle disappears because of the clear() method. The clear() method deletes the turtle’s drawing on the screen.

How to control the turtle with your keyboard


This section is going to be fun as we will control the turtle with the keyboard of our computer.

Before we write some codes, let me explain the following concepts.

1. onkey()
2. listen()

onkey()

This method is similar to onclick() method. The only differences is that the onclick() method responds to clicks on the
mouse while the onkey() method responds to commands from your computer keyboard.

The onkey() method accepts two arguments which are:

fun: this is a function without any argument


keyboard command: this is basically any alphabet on your keyboard (e.g n) or any keyboard command key.
e.g space, your direction keys(up, down). You have to pass this command as a string

listen()

I will avoid using any technical word because I’m as well bored with them. Basically, without including this method,
the turtle won’t obey your commands.

The listen() method is like a cane you use on a child to obey your instruction.

Alright, let’s write some codes.

Project 6:

Write a program to control the turtle to move up, down, left and right using the computer keyboard. The turtle should
move constantly to any pixels of your choice.

Include an undo action.

Open a new file editor and save the following code snippet as turtle_keyboard_control.py

keyboard control program


Python

39/47
1 from turtle import Turtle
2 t=Turtle()
3
4 def up():
5 if not(t.heading() == 90):
6 t.setheading(90)
7 t.fd(50)
8 else:
9 t.fd(50)
10
11 def down():
12 if not(t.heading() == 270):
13 t.setheading(270)
14 t.fd(50)
15 else:
16 t.fd(50)
17
18 def right():
19 if not (t.heading() == 0):
20 t.setheading(0)
21 t.fd(50)
22 else:
23 t.fd(50)
24
25 def left():
26 if not (t.heading() ==180):
27 t.setheading(180)
28 t.fd(50)
29 else:
30 t.fd(50)
31
32 def undo_button():
33 t.undo()
34
35 def keyboard_commands():
36 t.screen.onkey(up,"Up")
37 t.screen.onkey(down,"Down")
38 t.screen.onkey(right,"Right")
39 t.screen.onkey(left,"Left")
40 t.screen.onkey(undo_button,"End")
41 t.screen.listen()
42
43 keyboard_commands()
44 t.screen.mainloop()

Don’t let the long code snippet to confuse you.

I will quicky explain the program above.

I mentioned early that :

Angle 90 sets the turtle to face the North.

Angle 180 sets the turtle to face the West.

Angle 270 sets the turtle to face the South.

40/47
Angle 360 or 0 set turtle to face the East

Alright!!!…

Now the “if”, “ else “ and “not” tells the turtle that if it’s not facing the desired direction, that it should change the
direction.

t.heading() returns the current turtle’s current heading.

t.undo() undo the last action of the turtle.

The key commands are “Up”, “Down”, “Left”, “Right” and “End” which are your direction keys and end key on the
keyboard. Note that they all start with capital letters.

The rest of the code snippets are easy to understand.

stamp() method

This method basically pastes the turtle shape on the canvas on the current turtle’s position.

To illustrate this, open a new file editor and save the following code snippet as turtle_stamp.py

stamp method()
Python

1 from turtle import Turtle


2
3 t=Turtle()
4 t.up()
5 t.setx(-50)
6 t.down()
7 t.hideturtle()
8
9 for i in range(4):
10 t.fd(50)
11 t.stamp()

Here’s the output of the above code snippet.

Observing the above screenshot, you will see that the turtle shape appeared 4 times. This makes the concept of for
loop more practical. For every 50pixels to the east, a turtle shape will appear.

How to Determine the Position of the Turtle.

position() method:

This method returns the position of the turtle, both the coordinates of the x and y axis is returned.

xcor() method:

This method returns the x coordinate of the turtle.

41/47
ycor() method:

This method returns the y coordinate of the turtle.

One more last thing before I end this tutorial.

How to Change the Title of the Turtle Screen


The default title of the turtle screen is “Python Turtle Graphics”, which can be boring.

It will be fun if your name or your friend’s name is on it. Your friends will know that you’re a Pro programmer.

To change the title of the turtle screen, use the method screen.title(). This method only accepts a string.

To illustrate this method, open a new file editor and save the following code snippet as turtle_screen_title.py

Python

1 from turtle import Turtle


2
3 t=Turtle()
4
5 t.screen.title("Cool Python codes")

Here is the output of the program above.

42/47
How to change the title of Python turtle.

Here are some amazing drawings I did with Python Turtle including the code snippet.

Try and study the code snippet and do a lot of experiments to come up with new designs.

The below code snippet is saved as beautiful_circles.py

Circle spiral
Python

43/47
1 from turtle import Turtle
2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 colors=["red","yellow","purple"]
6 t.screen.tracer(0,0)
7
8 for x in range(100):
9 t.circle(x)
10 t.color(colors[x%3])
11 t.left(60)
12
13 t.screen.exitonclick()
14 t.screen.mainloop()

Here’s the output of the above code snippet.

Beautiful circles with Python Turtle

The below code snippet is saved as beautiful_square.py

Beautiful Square
Python
44/47
1 from turtle import Turtle
2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 colors=["blue","purple","red","yellow"]
6 t.screen.tracer(0,0)
7
8 for x in range(300):
9 t.color(colors[x%4])
10 t.fd(x)
11 t.left(90)
12
13 t.screen.exitonclick()
14 t.screen.mainloop()

Here’s the output of the code snippet above.

Beautiful Square

The below code snippet is saved as beautiful_spiral.py

Python

45/47
1 from turtle import Turtle
2
3 t=Turtle()
4 t.screen.bgcolor("black")
5 colors=["blue","purple","red","yellow","orange","brown"]
6 t.screen.tracer(0,0)
7
8 for x in range(300):
9 t.color(colors[x%6])
10 t.fd(x)
11 t.left(59)
12
13 t.screen.exitonclick()
14 t.screen.mainloop()

Here’s the output of the above code snippet.

beautiful spiral

You have come to the end of this tutorial.

Please don’t forget to:

46/47
Please if you have any questions or contributions, please leave it in the comment section.

Thanks for reading. If you enjoyed this tutorial, hit the share button. It would mean a lot to me and it helps other
people to see the tutorial.

47/47

You might also like