The Beginner's Guide to Python Turtle

The Beginner's Guide to Python Turtle

Table of Contents

Getting to Know the Python turtle Library

Getting started with turtle, moving the turtle, drawing a shape, drawing preset figures, changing the screen color, changing the screen title, changing the turtle size, changing the pen size, changing the turtle and pen color, filling in an image, changing the turtle shape, changing the pen speed, customizing in one line, picking the pen up and down, undoing changes, clearing the screen, resetting the environment, leaving a stamp, cloning your turtle, while loops, conditional statements, setting up the game environment, setting up the turtles and homes, creating the die, developing the game.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Turtle for Beginners

When I was a kid, I used to learn Logo , a programming language that involved a turtle that you could move around the screen with just a few commands. I remember feeling like a computer genius as I controlled this little object on my screen, and this was what got me interested in programming in the first place. The Python turtle library comes with a similar interactive feature that gives new programmers a taste of what it’s like to work with Python.

In this tutorial, you will:

  • Understand what the Python turtle library is
  • Learn how to set turtle up on your computer
  • Program with the Python turtle library
  • Grasp some important Python concepts and turtle commands
  • Develop a short but entertaining game using what you’ve learned

If you’re a beginner to Python, then this tutorial will help you as you take your first steps into the world of programming with the help of the Python turtle library!

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

turtle is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas. The onscreen pen that you use for drawing is called the turtle and this is what gives the library its name. In short, the Python turtle library helps new programmers get a feel for what programming with Python is like in a fun and interactive way.

turtle is mainly used to introduce children to the world of computers. It’s a straightforward yet versatile way to understand the concepts of Python. This makes it a great avenue for kids to take their first steps in Python programming. That being said, the Python turtle library is not restricted to little ones alone! It’s also proved extremely useful for adults who are trying their hands at Python, which makes it great for Python beginners .

With the Python turtle library, you can draw and create various types of shapes and images. Here’s a sample of the kinds of drawings you can make with turtle :

Cool, right? This is just one of many different drawings you can make using the Python turtle library. Most developers use turtle to draw shapes, create designs, and make images. Others use turtle to create mini-games and animations, just like the one you saw above.

Before you continue, there are two important things that you’ll need to do to make the most of this tutorial:

Python Environment: Make sure that you’re familiar with your programming environment . You can use applications like IDLE or Jupyter Notebook to program with turtle . However, if you’re not comfortable with them, then you can program with the REPL , which you’ll use in this tutorial.

Python Version: Ensure that you have version 3 of Python on your computer. If not, then you can download it from the Python website . For help setting things up, check out Python 3 Installation & Setup Guide .

The good thing about turtle is that it’s a built-in library, so you don’t need to install any new packages. All you need to do is import the library into your Python environment, which in this case would be the REPL. Once you open your REPL application, you can run Python 3 on it by typing the following line of code:

This calls Python 3 into your REPL application and opens up the environment for you.

Before you begin your Python programming, you need to understand what a library is. In the non-computer world, a library is a place where different types of books are stored. You can access these books at any time, take whatever information you need from them, and return them to the same place.

In the computer world, a library works similarly. By definition, a library is a set of important functions and methods that you can access to make your programming easier. The Python turtle library contains all the methods and functions that you’ll need to create your images. To access a Python library, you need to import it into your Python environment, like this:

Now that you have turtle in your Python environment, you can begin programming with it. turtle is a graphical library, which means you’ll need to create a separate window (called the screen ) to carry out each drawing command. You can create this screen by initializing a variable for it.

In Python, you use variables to store information that you’ll use later on in your program. You initialize a variable when you assign a starting value to it. Since the value of the variable isn’t constant, it can change several times during the execution of your program.

Now, to open the turtle screen, you initialize a variable for it in the following way:

You should see a separate window open up:

Python Turtle Initial Screen New

This window is called the screen . It’s where you can view the output of your code. The little black triangular shape in the middle of the screen is called the turtle .

Note : Keep in mind that when you name a variable, you need to pick a name that can be easily understood by anyone who’s looking at your program. However, you must also choose a name that’s convenient for you to use, especially because you’ll be calling it very often throughout your program!

For example, choosing a name like my_turtle_screen_name would be tedious to keep typing, while a name like Joe or a would appear to be very random. Using a single alphabet character, like s in this case, would be much more suitable. That’s because it’s short and sweet, and it’s clear to remember that the letter s refers to the screen .

Next, you initialize the variable t , which you’ll then use throughout the program to refer to the turtle:

Just like for the screen, you can also give this variable another name like a or Jane or even my_turtle , but in this case, you’ll stick with t .

You now have your screen and your turtle. The screen acts as a canvas, while the turtle acts like a pen. You can program the turtle to move around the screen. The turtle has certain changeable characteristics, like size, color, and speed. It always points in a specific direction, and will move in that direction unless you tell it otherwise:

  • When it’s up , it means that no line will be drawn when it moves.
  • When it’s down , it means that a line will be drawn when it moves.

In the next section, you’ll explore the different ways of programming with the Python turtle library.

Programming With turtle

The first thing you’ll learn when it comes to programming with the Python turtle library is how to make the turtle move in the direction you want it to go. Next, you’ll learn how to customize your turtle and its environment. Finally, you’ll learn a couple of extra commands with which you can perform some special tasks.

There are four directions that a turtle can move in:

The turtle moves .forward() or .backward() in the direction that it’s facing. You can change this direction by turning it .left() or .right() by a certain degree. You can try each of these commands like so:

When you run these commands, the turtle will turn right by ninety degrees, go forward by a hundred units, turn left by ninety degrees, and move backward by a hundred units. You can see how this looks in the image below:

You can use the shortened versions of these commands as well:

  • t.rt() instead of t.right()
  • t.fd() instead of t.forward()
  • t.lt() instead of t.left()
  • t.bk() instead of t.backward()

You can also draw a line from your current position to any other arbitrary position on the screen. This is done with the help of coordinates:

Python Turtle Coordinates New

The screen is divided into four quadrants . The point where the turtle is initially positioned at the beginning of your program is (0,0) . This is called Home . To move the turtle to any other area on the screen, you use .goto() and enter the coordinates like this:

Your output will look like this:

You’ve drawn a line from your current position to the point (100,100) on the screen.

To bring the turtle back to its home position, you type the following:

This is like a shortcut command that sends the turtle back to the point (0,0) . It’s quicker than typing t.goto(0,0) .

Now that you know the movements of the turtle, you can move on to making actual shapes. You can start by drawing polygons since they all consist of straight lines connected at certain angles. Here’s an example that you can try:

Well done! You’ve just drawn a square. In this way, the turtle can be programmed to create different shapes and images .

Now, try drawing a rectangle, using this code as a template. Remember, in a rectangle, all four sides are not equal. You’ll need to change the code accordingly. Once you do that, you can even try creating other polygons by increasing the number of sides and changing the angles.

Suppose you want to draw a circle . If you attempt to draw it in the same way as you drew the square, then it would be extremely tedious, and you’d have to spend a lot of time just for that one shape. Thankfully, the Python turtle library provides a solution for this. You can use a single command to draw a circle:

You’ll get an output like this:

The number within the brackets is the radius of the circle. You can increase or decrease the size of the circle by changing the value of its radius.

In the same way, you can also draw a dot , which is nothing but a filled-in circle. Type in this command:

You’ll get a filled-in circle like this:

Python Turtle Dot Update

The number within the brackets is the diameter of the dot. Just like with the circle, you can increase or decrease the size of the dot by changing the value of its diameter.

Great job so far! You’ve learned how to move the turtle around and create different shapes with it. In the next few sections, you’ll see how you can customize your turtle and its environment, based on your requirements.

By default, turtle always opens up a screen with a white background. However, you can change the color of the screen at any time using the following command:

You can replace "blue" with any other color. Try "green" or "red" . You’ll get a result like this:

You can use a variety of colors for your screen just by typing in their hex code number. To learn more about using different colors, check out the Python turtle library documentation .

Sometimes, you may want to change the title of your screen. You can make it more personal, like "My Turtle Program" , or more suitable to what you’re working on, like "Drawing Shapes With Turtle" . You can change the title of your screen with the help of this command:

Your title bar will now display this:

Python Turtle Screen Title Updated

In this way, you can change the heading of your screen according to your preference.

You can increase or decrease the size of the onscreen turtle to make it bigger or smaller. This changes only the size of the shape without affecting the output of the pen as it draws on the screen. Try typing in the following commands:

Your outputs will look like this:

The numbers given are the parameters for the size of the turtle:

  • Stretch length
  • Stretch width
  • Outline width

You can change these according to your preference. In the example given above, you can see a visible difference in the appearance of the turtle. For more information on how you can change the size of the turtle, check out the Python turtle library documentation .

The previous command changed the size of the turtle’s shape only. However, sometimes, you may need to increase or decrease the thickness of your pen. You can do this using the following command:

This results in an outcome like this:

As you can see, the size of your pen is now five times the original size (which was one). Try drawing some more lines of various sizes, and compare the difference in thickness between them.

When you first open a new screen, the turtle starts out as a black figure and draws with black ink. Based on your requirements, you can do two things:

  • Change the color of the turtle: This changes the fill color.
  • Change the color of the pen: This changes the outline or the ink color.

You can even choose both of these if you wish. Before you change the colors, increase the size of your turtle to help you see the color difference more clearly. Type in this code:

Now, to change the color of the turtle (or the fill), you type the following:

Your turtle will look like this:

Python Turtle Fill Color Red

To change the color of the pen (or the outline), you type the following:

Python Turtle Pen Color Updated Green

To change the color of both, you type the following:

Python Turtle Color Single Line Updated

Here, the first color is for the pen, and the second is for the fill. Note that changing the color of the pen and the fill also changes the color of the onscreen turtle accordingly.

Coloring in an image usually makes it look better, doesn’t it? The Python turtle library gives you the option to add color to your drawings. Try typing in the following code and see what happens:

When you execute this code, you’ll get a triangle that’s filled in with a solid color, like this:

When you use .begin_fill() , you’re telling your program that you’re going to be drawing a closed shape which will need to be filled in. Then, you use .end_fill() to indicate that you’re done creating your shape and it can now be filled in.

The initial shape of the turtle isn’t really a turtle, but a triangular figure. However, you can change the way the turtle looks , and you do have a couple of options when it comes to doing so. You can have a look at some of them by typing in the following commands:

The shape of the turtle will change accordingly, like this:

You have a couple of other options that you can try as well:

The classic shape is the original shape. Check out the Python turtle library documentation to learn more about the types of shapes that you can use.

The turtle generally moves at a moderate pace. If you want to decrease or increase the speed to make your turtle move slower or faster, then you can do so by typing the following:

This code will first decrease the speed and move the turtle forward, then increase the speed and move the turtle forward again, like this:

The speed can be any number ranging from 0 (the slowest speed) to 10 (the highest speed). You can play around with your code to see how fast or slow the turtle will go.

Suppose you want to set your turtle’s characteristics to the following:

  • Pen color: purple
  • Fill color: orange
  • Pen size: 10
  • Pen speed: 9

From what you’ve just learned, the code should look something like this:

It’s pretty long, but not that bad, right?

Now, just imagine if you had ten different turtles . Changing all of their characteristics would be extremely tiresome for you to do! The good news is that you can reduce your workload by altering the parameters in just a single line of code, like this:

This will give you a result like this:

This single line of code changed the entire pen, without you having to change each characteristic individually. To learn more about this command, check out the Python turtle library documentation .

Great job! Now that you’ve learned to customize your turtle and the screen, take a look at some other important commands that are required while drawing with the Python turtle library.

Sometimes, you may want to move your turtle to another point on the screen without drawing anything on the screen itself. To do this, you use .penup() . Then, when you want to start drawing again, you use .pendown() . Give it a shot using the code that you used previously to draw a square. Try typing the following code:

When you run this code, your output will look like this:

Python Turtle Pen Up Pen Down Edit

Here, you’ve obtained two parallel lines instead of a square by adding some extra commands in between the original program.

No matter how careful you are, there’s always a possibility of making a mistake. Don’t worry, though! The Python turtle library gives you the option to undo what you’ve done. If you want to undo the very last thing you did, then type in the following:

This undoes the last command that you ran. If you want to undo your last three commands, then you would type t.undo() three times.

Right now, you probably have a lot on your screen since you’ve started this tutorial. To make room for more, just type in the following command:

This will clean up your screen so that you can continue drawing. Note here that your variables will not change, and the turtle will remain in the same position. If you have other turtles on your screen other than the original turtle, then their drawings will not be cleared out unless you specifically call them out in your code.

You also have the option to start on a clean slate with a reset command. The screen will get cleared up, and the turtle’s settings will all be restored to their default parameters. All you need to to do is type in the following command:

This clears the screen and takes the turtle back to its home position. Your default settings, like the turtle’s size, shape, color, and other features, will also be restored.

Now that you’ve learned the fundamentals of programming with the Python turtle library, you’ll check out some bonus features that you may want to use while programming.

You have the option of leaving a stamp of your turtle on the screen, which is nothing but an imprint of the turtle. Try typing in this code to see how it works:

The numbers that appear are the turtle’s location or stamp ID . Now, if you want to remove a particular stamp, then just use the following:

This will clear the one with the stamp ID of 8 .

Sometimes, you may need to have more than one turtle on your screen. You’ll see an example of this later on in the final project. For now, you can get another turtle by cloning your current turtle into your environment. Try running this code to create a clone turtle, c , and then move both the turtles on the screen:

The output will look like this:

Now that you have an idea of some important commands from the Python turtle library, you’re ready to move on to a few more concepts that you’ll need to understand. These concepts are very much needed when it comes to programming in any language.

Using Loops and Conditional Statements

When you get into higher-level programming, you’ll find yourself using loops and conditional statements very often. That’s why, in this section, you’ll be going through a couple of turtle programs that make use of these types of commands. This will give you a practical approach when it comes to understanding these concepts. Before you begin, however, here are three definitions for you to keep in mind:

  • Loops are a set of instructions that are continuously repeated until a particular condition is satisfied.
  • Conditional statements carry out a certain task based on a condition that’s satisfied.
  • Indentations are used to define blocks of code, especially when using loops and conditional statements. In general, you create an indentation by tapping the Tab key on the keyboard.

Now, let’s go ahead and explore these commands!

Do you remember the program that you used to create a square? You had to repeat the same line of code four times, like this:

A much shorter way to do this is with the help of a for loop . Try running this code:

Here, the i is like a counter that starts from zero and keeps increasing by 1. When you say in range(4) , you’re telling the program that the value of this i should be less than 4. It will terminate the program before i reaches 4.

Here’s a breakdown of how the program works:

  • At i = 0, the turtle moves forward by 100 units and then turns 90 degrees to the right.
  • At i = 0 + 1 = 1, the turtle moves forward by 100 units and then turns 90 degrees to the right.
  • At i = 1 + 1 = 2, the turtle moves forward by 100 units and then turns 90 degrees to the right.
  • At i = 2 + 1 = 3, the turtle moves forward by 100 units and then turns 90 degrees to the right.

The turtle will then exit the loop. To check the value of i , type i and then press the Enter key. You’ll get the value of i equal to 3:

Note that the whitespace that comes before line 2 and line 3 in the program is the indentation . This indicates that all 3 lines form a single block of code. To learn more about for loops in Python, check out Python “for” Loops (Definite Iteration) .

The while loop is used to perform a certain task while a condition is still satisfied. If the condition is no longer satisfied, then your code will terminate the process. You can use a while loop to create a series of circles by typing in this code:

When you run this code, you’ll see the circles appearing one after the other, and each new circle will be larger than the previous one:

Here, n is used as a counter. You’ll need to specify by how much you want the value of n to increase in each loop. Take a look at this mini walk-through to see how the program works:

  • At n = 10, the turtle draws a circle with a radius of 10 units. After that, the value of n is increased by 10.
  • At n = 20, the turtle draws a circle with a radius of 20 units. Once again, the value of n is increased by 10.
  • At n = 30, the turtle draws a circle with a radius of 30 units. For the third time, the value of n is increased by 10.
  • At n = 40, the turtle draws a circle with a radius of 40 units. For the last time, the value of n is increased by 10.
  • At n = 50, n is no longer less than or equal to 40. The loop is terminated.

To read more about while loops, check out Python “while” Loops (Indefinite Iteration) .

You use conditional statements to check if a given condition is true. If it is, then the corresponding command is executed. Try typing in this program:

input() is used to obtain input from the user. Here, it will store the user’s response under the variable u . Next, it will compare the value of u with the condition provided and check whether the value of u is "yes" . If it’s "yes" , then your program draws a circle. If the user types in anything else, then the program won’t do anything.

Note: The comparison operator == indicates a comparison . It’s used to check if the value of something is equal to something else. The assignment operator = is used to assign a value to something. To learn more about the differences between the two, check out Operators and Expressions in Python .

When you add an else clause to an if statement, you can specify two results based on whether the condition is true or false. Let’s see this in a program:

Here, you tell the program to display a particular output even when the user does not say "yes" . You use print() to display some pre-defined characters on the screen.

Note that the user doesn’t need to type "no" . They can type anything else, in which case, the result will always be "Okay" , because you’re not explicitly telling the program that the user needs to type "no" . Not to worry, however, as that can be fixed. You can add an elif clause to provide the program with several conditions and their respective outputs, as you can observe here:

As you can see, this program now has more than one outcome, depending on the input it receives. Here’s how this code works:

  • If you type in "yes" , then the code processes the input and draws a circle, as per your instructions.
  • If you type in "no" , then the code prints out "Okay" and your program is terminated.
  • If you type in anything else, like "Hello" or "Sandwich" , then the code prints "Invalid Reply" and your program is terminated.

Note that this program is case-sensitive, so when you’re trying it out, be sure to put the strings in upper-case or lower-case accordingly.

To learn more about conditional statements, check out Conditional Statements in Python .

Final Project: The Python Turtle Race

So far, you’ve learned how to customize your turtle environment, program your turtle to move around the screen, and use loops and conditional statements to improve your code. Now it’s time for the most important part of your programming journey. In this section, you’ll be implementing all that you’ve learned into a single program by creating a fun game that you can play with your friends.

Before you begin, here’s what you need to know about the game:

The Objective: The player whose turtle reaches its home first wins the game.

How to Play:

  • Each player rolls a dice to get a number.
  • The player then moves their turtle by that many steps.
  • The players alternate turns until one of them wins.

The Structure:

  • Each player had a turtle indicated by a different color. You can have more than two players, but for the sake of this tutorial, you’ll be creating a two-player game.
  • Each turtle has a home position that it must reach.
  • Each player uses a die to choose a value at random for their turn. In your program, the die is represented by a list of numbers from 1 to 6.

Now that you’ve understood the logic of the game, you can go ahead and begin creating it! First, you’ll need to set up the environment.

Start by importing the Python turtle library. After this, import the built-in random library, which you’ll use randomly select an item from a list :

Once these libraries are successfully called into your environment, you can proceed with the rest of your program.

You now have to create the two turtles that will represent the players. Each turtle will be a different color, corresponding to the different players. Here, player one is green and player two is blue :

One you’ve created the turtles, you place them at their starting positions and make sure that these positions are aligned. Note that you created player two’s turtle by cloning player one’s turtle, changing its color, and placing it at a different starting point.

You now need to set up homes for the turtles. These homes will act as the finishing points for each turtle. Each of the turtles’ homes will be represented by a circle. Here, you need to make sure that both homes are equidistant from the starting point:

After drawing the respective homes, you send the turtles back to their starting positions:

Python Turtle Race Setup Updated

Awesome! The visual aspects of your game are complete. You can now create the die that you’ll be using to play the game.

You can create a virtual die for your game with a list , which is an ordered sequence of items. In real life, you might prepare grocery lists and to-do lists to help you stay organized. In Python, lists work in a similar way.

In this case, you’ll be using a list to create your die. First, you define your list of numbers in ascending order from 1 to 6. You can define a list by giving it a name and then enclosing its items within square brackets, like this:

This list has now become your die. To roll the dice, all you have to do is program your system to randomly select a number from it. The number that is selected will be considered as the output of the die.

It’s time to develop the code for the rest of the game. You’ll be using loops and conditional statements here, so you need to be careful with the indentations and spaces. To start, take a look at the steps your program will need to take to run the game:

  • Step 1: You’ll start by telling your program to check if either turtle has reached its home.
  • Step 2: If they haven’t, then you’ll tell your program to allow the players to continue trying.
  • Step 3: In each loop, you tell your program to roll the die by randomly picking a number from the list.
  • Step 4: You then tell it to move the respective turtle accordingly, with the number of steps based on the outcome of this random selection.

The program keeps repeating this process, and stops once one of the turtles reaches the goal. Here’s how the code looks:

Your final output will look a little something like this:

In summary, this is what the code is doing:

Line 1 sets up a for loop with a range from 1 to 20.

Lines 2 through 7 check if either player has reached their goal. If one of them has, then the program prints out the corresponding statement and breaks the loop.

Line 8 moves the program on to the next set of steps if neither player has won.

Line 9 prints out a statement asking player one to press the Enter key to roll the die.

Line 10 takes a random value from the list die and stores it in die_outcome .

Line 11 prints a statement prior to displaying the outcome of the dice roll.

Line 12 prints the dice outcome.

Line 14 multiplies this value by 20 to reduce the overall number of steps required to complete the game.

Line 15 moves player one’s turtle forward by this number of steps.

Lines 16 to 22 repeat these steps for player two.

The entire for loop is repeated until one of the player’s turtles reaches the final position.

Note: In Python, you use the asterisk ( * ) to indicate multiplication. This is known as an arithmetic operator . You can also use the plus sign ( + ) for addition, the minus sign ( - ) for subtraction, and a slash ( / ) for division. To learn more about arithmetic operators, check out the Arithmetic Operators section of Operators and Expressions in Python .

Remember, you can customize the game however you want, so go ahead and play around with it! You can add more turtles, change the colors, change the speed, or even create some obstacles to challenge your players. It’s all up to you as the developer of the game!

In this tutorial, you’ve learned how to program with the Python turtle library and grasped some very important programming concepts. You know how to deal with variable initialization, loops, conditional statements, indentations, lists, and operators. This is a great start for you, especially if you’re new to the Python programming language!

Now you can:

  • Set up the Python turtle library
  • Move your turtle around
  • Customize your turtle and its environment
  • Program your turtle
  • Use basic programming concepts
  • Create a game that you can play with friends

Now you’re ready to venture into some higher-level Python programming. To progress further in your Python journey, check out Introduction to Python and 11 Beginner Tips for Learning Python Programming . Just remember to work hard and keep practicing, and you’ll find that you’re a Python expert in no time!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Nikita Silaparasetty

Nikita Silaparasetty

Nikita is an avid Pythonista and writes for Real Python.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Python Turtle for Beginners

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.

python turtle assignment

  • Python »
  • 3.12.5 Documentation »
  • The Python Standard Library »
  • Program Frameworks »
  • turtle — Turtle graphics
  • Theme Auto Light Dark |

turtle — Turtle graphics ¶

Source code: Lib/turtle.py

Introduction ¶

Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo , developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

In Python, turtle graphics provides a representation of a physical “turtle” (a little robot with a pen) that draws on a sheet of paper on the floor.

It’s an effective and well-proven way for learners to encounter programming concepts and interaction with software, as it provides instant, visible feedback. It also provides convenient access to graphical output in general.

Turtle drawing was originally created as an educational tool, to be used by teachers in the classroom. For the programmer who needs to produce some graphical output it can be a way to do that without the overhead of introducing more complex or external libraries into their work.

New users should start here. In this tutorial we’ll explore some of the basics of turtle drawing.

Starting a turtle environment ¶

In a Python shell, import all the objects of the turtle module:

If you run into a No module named '_tkinter' error, you’ll have to install the Tk interface package on your system.

Basic drawing ¶

Send the turtle forward 100 steps:

You should see (most likely, in a new window on your display) a line drawn by the turtle, heading East. Change the direction of the turtle, so that it turns 120 degrees left (anti-clockwise):

Let’s continue by drawing a triangle:

Notice how the turtle, represented by an arrow, points in different directions as you steer it.

Experiment with those commands, and also with backward() and right() .

Pen control ¶

Try changing the color - for example, color('blue') - and width of the line - for example, width(3) - and then drawing again.

You can also move the turtle around without drawing, by lifting up the pen: up() before moving. To start drawing again, use down() .

The turtle’s position ¶

Send your turtle back to its starting-point (useful if it has disappeared off-screen):

The home position is at the center of the turtle’s screen. If you ever need to know them, get the turtle’s x-y coordinates with:

Home is at (0, 0) .

And after a while, it will probably help to clear the window so we can start anew:

Making algorithmic patterns ¶

Using loops, it’s possible to build up geometric patterns:

- which of course, are limited only by the imagination!

Let’s draw the star shape at the top of this page. We want red lines, filled in with yellow:

Just as up() and down() determine whether lines will be drawn, filling can be turned on and off:

Next we’ll create a loop:

abs(pos()) < 1 is a good way to know when the turtle is back at its home position.

Finally, complete the filling:

(Note that filling only actually takes place when you give the end_fill() command.)

This section covers some typical turtle use-cases and approaches.

Get started as quickly as possible ¶

One of the joys of turtle graphics is the immediate, visual feedback that’s available from simple commands - it’s an excellent way to introduce children to programming ideas, with a minimum of overhead (not just children, of course).

The turtle module makes this possible by exposing all its basic functionality as functions, available with from turtle import * . The turtle graphics tutorial covers this approach.

It’s worth noting that many of the turtle commands also have even more terse equivalents, such as fd() for forward() . These are especially useful when working with learners for whom typing is not a skill.

You’ll need to have the Tk interface package installed on your system for turtle graphics to work. Be warned that this is not always straightforward, so check this in advance if you’re planning to use turtle graphics with a learner.

Use the turtle module namespace ¶

Using from turtle import * is convenient - but be warned that it imports a rather large collection of objects, and if you’re doing anything but turtle graphics you run the risk of a name conflict (this becomes even more an issue if you’re using turtle graphics in a script where other modules might be imported).

The solution is to use import turtle - fd() becomes turtle.fd() , width() becomes turtle.width() and so on. (If typing “turtle” over and over again becomes tedious, use for example import turtle as t instead.)

Use turtle graphics in a script ¶

It’s recommended to use the turtle module namespace as described immediately above, for example:

Another step is also required though - as soon as the script ends, Python will also close the turtle’s window. Add:

to the end of the script. The script will now wait to be dismissed and will not exit until it is terminated, for example by closing the turtle graphics window.

Use object-oriented turtle graphics ¶

Explanation of the object-oriented interface

Other than for very basic introductory purposes, or for trying things out as quickly as possible, it’s more usual and much more powerful to use the object-oriented approach to turtle graphics. For example, this allows multiple turtles on screen at once.

In this approach, the various turtle commands are methods of objects (mostly of Turtle objects). You can use the object-oriented approach in the shell, but it would be more typical in a Python script.

The example above then becomes:

Note the last line. t.screen is an instance of the Screen that a Turtle instance exists on; it’s created automatically along with the turtle.

The turtle’s screen can be customised, for example:

Turtle graphics reference ¶

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

Turtle methods ¶

Methods of turtlescreen/screen ¶, methods of rawturtle/turtle and corresponding functions ¶.

Most of the examples in this section refer to a Turtle instance called turtle .

Turtle motion ¶

distance – a number (integer or float)

Move the turtle forward by the specified distance , in the direction the turtle is headed.

distance – a number

Move the turtle backward by distance , opposite to the direction the turtle is headed. Do not change the turtle’s heading.

angle – a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode() .

Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode() .

x – a number or a pair/vector of numbers

y – a number or None

If y is None , x must be a pair of coordinates or a Vec2D (e.g. as returned by pos() ).

Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.

x – a number or None

fill_gap – a boolean

Move turtle to an absolute position. Unlike goto(x, y), a line will not be drawn. The turtle’s orientation does not change. If currently filling, the polygon(s) teleported from will be filled after leaving, and filling will begin again after teleporting. This can be disabled with fill_gap=True, which makes the imaginary line traveled during teleporting act as a fill barrier like in goto(x, y).

Added in version 3.12.

x – a number (integer or float)

Set the turtle’s first coordinate to x , leave second coordinate unchanged.

y – a number (integer or float)

Set the turtle’s second coordinate to y , leave first coordinate unchanged.

to_angle – a number (integer or float)

Set the orientation of the turtle to to_angle . Here are some common directions in degrees:

standard mode

logo mode

0 - east

0 - north

90 - north

90 - east

180 - west

180 - south

270 - south

270 - west

Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation (which depends on the mode, see mode() ).

radius – a number

extent – a number (or None )

steps – an integer (or None )

Draw a circle with given radius . The center is radius units left of the turtle; extent – an angle – determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the direction of the turtle is changed by the amount of extent .

As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons.

size – an integer >= 1 (if given)

color – a colorstring or a numeric color tuple

Draw a circular dot with diameter size , using color . If size is not given, the maximum of pensize+4 and 2*pensize is used.

Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id) .

stampid – an integer, must be return value of previous stamp() call

Delete stamp with given stampid .

n – an integer (or None )

Delete all or first/last n of turtle’s stamps. If n is None , delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps.

Undo (repeatedly) the last turtle action(s). Number of available undo actions is determined by the size of the undobuffer.

speed – an integer in the range 0..10 or a speedstring (see below)

Set the turtle’s speed to an integer value in the range 0..10. If no argument is given, return current speed.

If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues as follows:

“fastest”: 0

“normal”: 6

“slowest”: 1

Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning.

Attention: speed = 0 means that no animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly.

Tell Turtle’s state ¶

Return the turtle’s current location (x,y) (as a Vec2D vector).

x – a number or a pair/vector of numbers or a turtle instance

y – a number if x is a number, else None

Return the angle between the line from turtle position to position specified by (x,y), the vector or the other turtle. This depends on the turtle’s start orientation which depends on the mode - “standard”/”world” or “logo”.

Return the turtle’s x coordinate.

Return the turtle’s y coordinate.

Return the turtle’s current heading (value depends on the turtle mode, see mode() ).

Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units.

Settings for measurement ¶

fullcircle – a number

Set angle measurement units, i.e. set number of “degrees” for a full circle. Default value is 360 degrees.

Set the angle measurement units to radians. Equivalent to degrees(2*math.pi) .

Drawing state ¶

Pull the pen down – drawing when moving.

Pull the pen up – no drawing when moving.

width – a positive number

Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned.

pen – a dictionary with some or all of the below listed keys

pendict – one or more keyword-arguments with the below listed keys as keywords

Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs:

“shown”: True/False

“pendown”: True/False

“pencolor”: color-string or color-tuple

“fillcolor”: color-string or color-tuple

“pensize”: positive number

“speed”: number in range 0..10

“resizemode”: “auto” or “user” or “noresize”

“stretchfactor”: (positive number, positive number)

“outline”: positive number

“tilt”: number

This dictionary can be used as argument for a subsequent call to pen() to restore the former pen-state. Moreover one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement.

Return True if pen is down, False if it’s up.

Color control ¶

Return or set the pencolor.

Four input formats are allowed:

Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color/pencolor/fillcolor call.

Set pencolor to colorstring , which is a Tk color specification string, such as "red" , "yellow" , or "#33cc8c" .

Set pencolor to the RGB color represented by the tuple of r , g , and b . Each of r , g , and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode() ).

Set pencolor to the RGB color represented by r , g , and b . Each of r , g , and b must be in the range 0..colormode.

If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor.

Return or set the fillcolor.

Return the current fillcolor as color specification string, possibly in tuple format (see example). May be used as input to another color/pencolor/fillcolor call.

Set fillcolor to colorstring , which is a Tk color specification string, such as "red" , "yellow" , or "#33cc8c" .

Set fillcolor to the RGB color represented by the tuple of r , g , and b . Each of r , g , and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode() ).

Set fillcolor to the RGB color represented by r , g , and b . Each of r , g , and b must be in the range 0..colormode.

If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.

Return or set pencolor and fillcolor.

Several input formats are allowed. They use 0 to 3 arguments as follows:

Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by pencolor() and fillcolor() .

Inputs as in pencolor() , set both, fillcolor and pencolor, to the given value.

Equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used.

If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors.

See also: Screen method colormode() .

Return fillstate ( True if filling, False else).

To be called just before drawing a shape to be filled.

Fill the shape drawn after the last call to begin_fill() .

Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps. For example, the Turtle star above may be either all yellow or have some white regions.

More drawing control ¶

Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the default values.

Delete the turtle’s drawings from the screen. Do not move turtle. State and position of the turtle as well as drawings of other turtles are not affected.

arg – object to be written to the TurtleScreen

move – True/False

align – one of the strings “left”, “center” or right”

font – a triple (fontname, fontsize, fonttype)

Write text - the string representation of arg - at the current turtle position according to align (“left”, “center” or “right”) and with the given font. If move is true, the pen is moved to the bottom-right corner of the text. By default, move is False .

Turtle state ¶

Visibility ¶.

Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably.

Make the turtle visible.

Return True if the Turtle is shown, False if it’s hidden.

Appearance ¶

name – a string which is a valid shapename

Set turtle shape to shape with given name or, if name is not given, return name of current shape. Shape with name must exist in the TurtleScreen’s shape dictionary. Initially there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. To learn about how to deal with shapes see Screen method register_shape() .

rmode – one of the strings “auto”, “user”, “noresize”

Set resizemode to one of the values: “auto”, “user”, “noresize”. If rmode is not given, return current resizemode. Different resizemodes have the following effects:

“auto”: adapts the appearance of the turtle corresponding to the value of pensize.

“user”: adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize() .

“noresize”: no adaption of the turtle’s appearance takes place.

resizemode("user") is called by shapesize() when used with arguments.

stretch_wid – positive number

stretch_len – positive number

outline – positive number

Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shape’s outline.

shear – number (optional)

Set or return the current shearfactor. Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. Do not change the turtle’s heading (direction of movement). If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared.

angle – a number

Rotate the turtleshape by angle from its current tilt-angle, but do not change the turtle’s heading (direction of movement).

Rotate the turtleshape to point in the direction specified by angle , regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement).

Deprecated since version 3.1.

angle – a number (optional)

Set or return the current tilt-angle. If angle is given, rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement). If angle is not given: return the current tilt-angle, i. e. the angle between the orientation of the turtleshape and the heading of the turtle (its direction of movement).

t11 – a number (optional)

t12 – a number (optional)

t21 – a number (optional)

Set or return the current transformation matrix of the turtle shape.

If none of the matrix elements are given, return the transformation matrix as a tuple of 4 elements. Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, t22. The determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised. Modify stretchfactor, shearfactor and tiltangle according to the given matrix.

Return the current shape polygon as tuple of coordinate pairs. This can be used to define a new shape or components of a compound shape.

Using events ¶

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

btn – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True , a new binding will be added, otherwise it will replace a former binding

Bind fun to mouse-click events on this turtle. If fun is None , existing bindings are removed. Example for the anonymous turtle, i.e. the procedural way:

Bind fun to mouse-button-release events on this turtle. If fun is None , existing bindings are removed.

Bind fun to mouse-move events on this turtle. If fun is None , existing bindings are removed.

Remark: Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle.

Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down).

Special Turtle methods ¶

Start recording the vertices of a polygon. Current turtle position is first vertex of polygon.

Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. This will be connected with the first vertex.

Return the last recorded polygon.

Create and return a clone of the turtle with same position, heading and turtle properties.

Return the Turtle object itself. Only reasonable use: as a function to return the “anonymous turtle”:

Return the TurtleScreen object the turtle is drawing on. TurtleScreen methods can then be called for that object.

size – an integer or None

Set or disable undobuffer. If size is an integer, an empty undobuffer of given size is installed. size gives the maximum number of turtle actions that can be undone by the undo() method/function. If size is None , the undobuffer is disabled.

Return number of entries in the undobuffer.

Compound shapes ¶

To use compound turtle shapes, which consist of several polygons of different color, you must use the helper class Shape explicitly as described below:

Create an empty Shape object of type “compound”.

Add as many components to this object as desired, using the addcomponent() method.

For example:

Now add the Shape to the Screen’s shapelist and use it:

The Shape class is used internally by the register_shape() method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above!

Methods of TurtleScreen/Screen and corresponding functions ¶

Most of the examples in this section refer to a TurtleScreen instance called screen .

Window control ¶

args – a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers

Set or return background color of the TurtleScreen.

picname – a string, name of a gif-file or "nopic" , or None

Set background image or return name of current backgroundimage. If picname is a filename, set the corresponding image as background. If picname is "nopic" , delete background image, if present. If picname is None , return the filename of the current backgroundimage.

This TurtleScreen method is available as a global function only under the name clearscreen . The global function clear is a different one derived from the Turtle method clear .

Delete all drawings and all turtles from the TurtleScreen. Reset the now empty TurtleScreen to its initial state: white background, no background image, no event bindings and tracing on.

This TurtleScreen method is available as a global function only under the name resetscreen . The global function reset is another one derived from the Turtle method reset .

Reset all Turtles on the Screen to their initial state.

canvwidth – positive integer, new width of canvas in pixels

canvheight – positive integer, new height of canvas in pixels

bg – colorstring or color-tuple, new background color

If no arguments are given, return current (canvaswidth, canvasheight). Else resize the canvas the turtles are drawing on. Do not alter the drawing window. To observe hidden parts of the canvas, use the scrollbars. With this method, one can make visible those parts of a drawing which were outside the canvas before.

e.g. to search for an erroneously escaped turtle ;-)

llx – a number, x-coordinate of lower left corner of canvas

lly – a number, y-coordinate of lower left corner of canvas

urx – a number, x-coordinate of upper right corner of canvas

ury – a number, y-coordinate of upper right corner of canvas

Set up user-defined coordinate system and switch to mode “world” if necessary. This performs a screen.reset() . If mode “world” is already active, all drawings are redrawn according to the new coordinates.

ATTENTION : in user-defined coordinate systems angles may appear distorted.

Animation control ¶

delay – positive integer

Set or return the drawing delay in milliseconds. (This is approximately the time interval between two consecutive canvas updates.) The longer the drawing delay, the slower the animation.

Optional argument:

n – nonnegative integer

delay – nonnegative integer

Turn turtle animation on/off and set delay for update drawings. If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) When called without arguments, returns the currently stored value of n. Second argument sets delay value (see delay() ).

Perform a TurtleScreen update. To be used when tracer is turned off.

See also the RawTurtle/Turtle method speed() .

Using screen events ¶

Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are provided in order to be able to pass listen() to the onclick method.

fun – a function with no arguments or None

key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)

Bind fun to key-release event of key. If fun is None , event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. (See method listen() .)

Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Remark: in order to be able to register key-events, TurtleScreen must have focus. (See method listen() .)

Bind fun to mouse-click events on this screen. If fun is None , existing bindings are removed.

Example for a TurtleScreen instance named screen and a Turtle instance named turtle :

This TurtleScreen method is available as a global function only under the name onscreenclick . The global function onclick is another one derived from the Turtle method onclick .

fun – a function with no arguments

t – a number >= 0

Install a timer that calls fun after t milliseconds.

Starts event loop - calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics.

Input methods ¶

title – string

prompt – string

Pop up a dialog window for input of a string. Parameter title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input. If the dialog is canceled, return None .

default – number (optional)

minval – number (optional)

maxval – number (optional)

Pop up a dialog window for input of a number. title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value, minval: minimum value for input, maxval: maximum value for input. The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None .

Settings and special methods ¶

mode – one of the strings “standard”, “logo” or “world”

Set turtle mode (“standard”, “logo” or “world”) and perform reset. If mode is not given, current mode is returned.

Mode “standard” is compatible with old turtle . Mode “logo” is compatible with most Logo turtle graphics. Mode “world” uses user-defined “world coordinates”. Attention : in this mode angles appear distorted if x/y unit-ratio doesn’t equal 1.

Mode

Initial turtle heading

positive angles

“standard”

to the right (east)

counterclockwise

“logo”

upward (north)

clockwise

cmode – one of the values 1.0 or 255

Return the colormode or set it to 1.0 or 255. Subsequently r , g , b values of color triples have to be in the range 0..*cmode*.

Return the Canvas of this TurtleScreen. Useful for insiders who know what to do with a Tkinter Canvas.

Return a list of names of all currently available turtle shapes.

There are three different ways to call this function:

name is the name of a gif-file and shape is None : Install the corresponding image shape.

Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!

name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape.

name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape.

Add a turtle shape to TurtleScreen’s shapelist. Only thusly registered shapes can be used by issuing the command shape(shapename) .

Return the list of turtles on the screen.

Return the height of the turtle window.

Return the width of the turtle window.

Methods specific to Screen, not inherited from TurtleScreen ¶

Shut the turtlegraphics window.

Bind bye() method to mouse clicks on the Screen.

If the value “using_IDLE” in the configuration dictionary is False (default value), also enter mainloop. Remark: If IDLE with the -n switch (no subprocess) is used, this value should be set to True in turtle.cfg . In this case IDLE’s own mainloop is active also for the client script.

Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a turtle.cfg file.

width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen

height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen

startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None , center window horizontally

starty – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None , center window vertically

titlestring – a string that is shown in the titlebar of the turtle graphics window

Set title of turtle window to titlestring .

Public classes ¶

canvas – a tkinter.Canvas , a ScrolledCanvas or a TurtleScreen

Create a turtle. The turtle has all methods described above as “methods of Turtle/RawTurtle”.

Subclass of RawTurtle, has the same interface but draws on a default Screen object created automatically when needed for the first time.

cv – a tkinter.Canvas

Provides screen oriented methods like bgcolor() etc. that are described above.

Subclass of TurtleScreen, with four methods added .

master – some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added

Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.

type_ – one of the strings “polygon”, “image”, “compound”

Data structure modeling shapes. The pair (type_, data) must follow this specification:

“polygon”

a polygon-tuple, i.e. a tuple of pairs of coordinates

“image”

an image (in this form only used internally!)

“compound”

(a compound shape has to be constructed using the method)

poly – a polygon, i.e. a tuple of pairs of numbers

fill – a color the poly will be filled with

outline – a color for the poly’s outline (if given)

See Compound shapes .

A two-dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs too. Derived from tuple, so a vector is a tuple!

Provides (for a , b vectors, k number):

a + b vector addition

a - b vector subtraction

a * b inner product

k * a and a * k multiplication with scalar

abs(a) absolute value of a

a.rotate(angle) rotation

Explanation ¶

A turtle object draws on a screen object, and there a number of key classes in the turtle object-oriented interface that can be used to create them and relate them to each other.

A Turtle instance will automatically create a Screen instance if one is not already present.

Turtle is a subclass of RawTurtle , which doesn’t automatically create a drawing surface - a canvas will need to be provided or created for it. The canvas can be a tkinter.Canvas , ScrolledCanvas or TurtleScreen .

TurtleScreen is the basic drawing surface for a turtle. Screen is a subclass of TurtleScreen , and includes some additional methods for managing its appearance (including size and title) and behaviour. TurtleScreen ’s constructor needs a tkinter.Canvas or a ScrolledCanvas as an argument.

The functional interface for turtle graphics uses the various methods of Turtle and TurtleScreen / Screen . Behind the scenes, a screen object is automatically created whenever a function derived from a Screen method is called. Similarly, a turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen, the object-oriented interface must be used.

Help and configuration ¶

How to use help ¶.

The public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:

When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.

Calling help() on methods or functions displays the docstrings:

The docstrings of the functions which are derived from methods have a modified form:

These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.

Translation of docstrings into different languages ¶

There is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle.

filename – a string, used as filename

Create and write docstring-dictionary to a Python script with the given filename. This function has to be called explicitly (it is not used by the turtle graphics classes). The docstring dictionary will be written to the Python script filename .py . It is intended to serve as a template for translation of the docstrings into different languages.

If you (or your students) want to use turtle with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. turtle_docstringdict_german.py .

If you have an appropriate entry in your turtle.cfg file this dictionary will be read in at import time and will replace the original English docstrings.

At the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to glingl @ aon . at .)

How to configure Screen and Turtles ¶

The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.

If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its settings.

The built in configuration would correspond to the following turtle.cfg :

Short explanation of selected entries:

The first four lines correspond to the arguments of the Screen.setup method.

Line 5 and 6 correspond to the arguments of the method Screen.screensize .

shape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try help(shape) .

If you want to use no fill color (i.e. make the turtle transparent), you have to write fillcolor = "" (but all nonempty strings must not have quotes in the cfg file).

If you want to reflect the turtle its state, you have to use resizemode = auto .

If you set e.g. language = italian the docstringdict turtle_docstringdict_italian.py will be loaded at import time (if present on the import path, e.g. in the same directory as turtle ).

The entries exampleturtle and examplescreen define the names of these objects as they occur in the docstrings. The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.

using_IDLE : Set this to True if you regularly work with IDLE and its -n switch (“no subprocess”). This will prevent exitonclick() to enter the mainloop.

There can be a turtle.cfg file in the directory where turtle is stored and an additional one in the current working directory. The latter will override the settings of the first one.

The Lib/turtledemo directory contains a turtle.cfg file. You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer).

turtledemo — Demo scripts ¶

The turtledemo package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows:

Alternatively, you can run the demo scripts individually. For example,

The turtledemo package directory contains:

A demo viewer __main__.py which can be used to view the sourcecode of the scripts and run them at the same time.

Multiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone.

A turtle.cfg file which serves as an example of how to write and use such files.

The demo scripts are:

Name

Description

Features

bytedesign

complex classical turtle graphics pattern

, delay,

chaos

graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations

world coordinates

clock

analog clock showing time of your computer

turtles as clock’s hands, ontimer

colormixer

experiment with r, g, b

forest

3 breadth-first trees

randomization

fractalcurves

Hilbert & Koch curves

recursion

lindenmayer

ethnomathematics (indian kolams)

L-System

minimal_hanoi

Towers of Hanoi

Rectangular Turtles as Hanoi discs (shape, shapesize)

nim

play the classical nim game with three heaps of sticks against the computer.

turtles as nimsticks, event driven (mouse, keyboard)

paint

super minimalistic drawing program

peace

elementary

turtle: appearance and animation

penrose

aperiodic tiling with kites and darts

planet_and_moon

simulation of gravitational system

compound shapes,

rosette

a pattern from the wikipedia article on turtle graphics

,

round_dance

dancing turtles rotating pairwise in opposite direction

compound shapes, clone shapesize, tilt, get_shapepoly, update

sorting_animate

visual demonstration of different sorting methods

simple alignment, randomization

tree

a (graphical) breadth first tree (using generators)

two_canvases

simple design

turtles on two canvases

yinyang

another elementary example

Changes since Python 2.6 ¶

The methods Turtle.tracer , Turtle.window_width and Turtle.window_height have been eliminated. Methods with these names and functionality are now available only as methods of Screen . The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen / Screen methods.)

The method Turtle.fill() has been eliminated. The behaviour of begin_fill() and end_fill() have changed slightly: now every filling process must be completed with an end_fill() call.

A method Turtle.filling has been added. It returns a boolean value: True if a filling process is under way, False otherwise. This behaviour corresponds to a fill() call without arguments in Python 2.6.

Changes since Python 3.0 ¶

The Turtle methods shearfactor() , shapetransform() and get_shapepoly() have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. tiltangle() has been enhanced in functionality: it now can be used to get or set the tilt angle. settiltangle() has been deprecated.

The Screen method onkeypress() has been added as a complement to onkey() . As the latter binds actions to the key release event, an alias: onkeyrelease() was also added for it.

The method Screen.mainloop has been added, so there is no longer a need to use the standalone mainloop() function when working with Screen and Turtle objects.

Two input methods have been added: Screen.textinput and Screen.numinput . These pop up input dialogs and return strings and numbers respectively.

Two example scripts tdemo_nim.py and tdemo_round_dance.py have been added to the Lib/turtledemo directory.

Table of Contents

  • Introduction
  • Starting a turtle environment
  • Pen control
  • The turtle’s position
  • Making algorithmic patterns
  • Get started as quickly as possible
  • Use the turtle module namespace
  • Use turtle graphics in a script
  • Use object-oriented turtle graphics
  • Turtle methods
  • Methods of TurtleScreen/Screen
  • Turtle motion
  • Tell Turtle’s state
  • Settings for measurement
  • Drawing state
  • Color control
  • More drawing control
  • Using events
  • Special Turtle methods
  • Compound shapes
  • Window control
  • Animation control
  • Using screen events
  • Input methods
  • Settings and special methods
  • Methods specific to Screen, not inherited from TurtleScreen
  • Public classes
  • Explanation
  • How to use help
  • Translation of docstrings into different languages
  • How to configure Screen and Turtles
  • turtledemo — Demo scripts
  • Changes since Python 2.6
  • Changes since Python 3.0

Previous topic

Program Frameworks

cmd — Support for line-oriented command interpreters

  • Report a Bug
  • Show Source
  • Table of Contents
  • ActiveCode Work Area
  • 4.1.1. Inner Squares
  • 4.1.2. Square Logo
  • 4.1.3. Overlapped Squares
  • 4.1.4. Bonus - If You Are Done Before Others
  • 4.2. Turtle Graphics Assignment

4. Turtle Drawing Practice ¶

Quick Overview of Day

Use for loops and functions to draw shapes elegantly. Continue working on a Python turtle graphics assignment, focused on repetition and conditionals.

  • CS20-CP1 Apply various problem-solving strategies to solve programming problems throughout Computer Science 20.
  • CS20-FP1 Utilize different data types, including integer, floating point, Boolean and string, to solve programming problems.
  • CS20-FP2 Investigate how control structures affect program flow.
  • CS20-FP3 Construct and utilize functions to create reusable pieces of code.

4.1. Practice Problems ¶

4.1.1. inner squares ¶.

Define a function similar to draw_square(my_turtle, side_length) and call it twice to draw the shape above. You may find it helpful define a new version of of this function, instead of reusing the one from yesterday. Perhaps you might not start in the same location as we did the last time we drew a square?

4.1.2. Square Logo ¶

Draw the shape above. Depending on how you defined the function in the problem above, you may be able to easily use reuse your function.

4.1.3. Overlapped Squares ¶

Draw the shape above. Depending on how you defined your earlier function(s) in the problems aboves, you may be able to easily use reuse your function(s).

4.1.4. Bonus - If You Are Done Before Others ¶

Draw the shape above. Think carefully about how you might be able to draw this elegantly (efficiently and readably)! Creating an adapted version of one of your previous functions isn’t a bad idea…

4.2. Turtle Graphics Assignment ¶

Use the rest of this class time to keep working on your current Python assignment (possibly a turtle graphics drawing, with a focus on looping and conditionals).

Learn Python

# The turtle library

(opens new window) is a standard Python library that allows you to create shapes and drawings in a virtual canvas. Imagine you start at (0, 0) in a x-y plane. With the help of turtle library, you can move a virtual pen to draw lines and fill with colors to make creative drawings.

Let's see how it goes in action.

# Getting started

Simply import turtle to get started. Take a look at the example from the Python docs and get the feeling of what turtle can offer.

Now let's learn the basics of turtle .

python turtle assignment

(opens new window) will show the interactive canvas. You can see the triangular figure ("turtle") in the middle of the screen. That's where our virtual penpoint locates.

(opens new window) .

python turtle assignment

(opens new window)

python turtle assignment

(opens new window) can change the default triangular shape to your liking. Available options include "arrow", "turtle", "circle", "square", "triangle", and "classic".

python turtle assignment

In fact, pencolor() also determines the color of the trace and fillcolor() would change the color of a filled shape. See the examples below.

(opens new window) by a specific degree. By default, the turtle will draw when it moves. Check the commands and the associated results.

First, we move the turtle forward by 100.

python turtle assignment

Then, we turn the turtle to the right by 45 degrees. Notice the turtle head turned.

python turtle assignment

Next, we move backward by 50.

python turtle assignment

This time, we turn the turtle to the left by 90 degrees. See the turtle head now is pointing to upper right.

python turtle assignment

Lastly the turtle continues to move forward by 100

python turtle assignment

And home() will send the turtle back to the initial location.

python turtle assignment

(opens new window) would make the turtle move in circle.

python turtle assignment

(opens new window) in which the turtle moves.

python turtle assignment

When wrapped by begin_fill() and end_fill() , the area determined by the path of the turtle's movement will be filled with color.

Let's use some of the previous movements for example.

python turtle assignment

Notice that a straight imaginary line will draw automatically if the ending location is different from the initial one.

python turtle assignment

# Multiple Turtles

We can create additional turtles if needed.

python turtle assignment

# Moving without drawing

The turtle will not draw if we lift the pen up. To resume drawing, simply pen down.

python turtle assignment

# Assignment 15

Create a Python script named turtle_square.py which draws a red square with length of 100.

Canvas closing too soon?

Add turtle.done() at the end of script so that the canvas won't close automatically.

The drawing would look like as below.

python turtle assignment

# Assignment 16

Create a Python script named turtle_triangle.py which draws a green triangle with vertices at (0,0), (100, 40), and (-50, 80).

python turtle assignment

# Assignment 17

Create a Python script named turtle_race.py which simulates a race between two turtles, a blue turtle and a green one. The first to move 200 forward would win the race. The race is turn by turn. In each turn both turtles roll a dice to determine how far they move forward. For example, if the blue turtle rolls a six, it moves 6 forward.

Also show the winner at the title bar when the race ends.

The drawing would look like as below on completion.

python turtle assignment

← A Tiny Challenge Another Challenge →

Python Geeks

Learn Python Programming from Scratch

  • Learn Python

Python Turtle for Beginners

Get ready to crack interviews of top MNCs with Placement-ready courses Learn More!

Are you interested in exploring the world of programming and unleashing your creativity? Look no further! Python Turtle is an excellent tool for beginners to dive into the exciting realm of coding. With Python Turtle, you can create beautiful graphics, draw shapes, and bring your ideas to life using a simple and intuitive interface. In this blog, we will embark on a journey to understand the fundamentals of Python Turtle and learn how to create mesmerizing visuals using code. So, let’s get started and discover the magic of Python Turtle!

Understanding the Topic: Python Turtle

Python Turtle is a built-in library in Python that provides a fun and interactive way to learn programming concepts. It is based on the Logo programming language and allows users to draw graphics and shapes on a screen using a turtle metaphor. The turtle acts as a virtual pen, which can move, turn, and draw lines as instructed by the user. With Python Turtle, beginners can grasp programming concepts such as loops, conditionals, and functions while creating visually appealing designs.

In this blog, we will cover the following topics related to Python Turtle:

  • Introduction to Python Turtle and its features
  • Basic turtle movements and commands
  • Drawing shapes and patterns with Python Turtle
  • Using loops and conditionals for more complex designs
  • Customizing colors, pen size, and speed
  • Saving and sharing your Turtle graphics
  • Fun projects and creative applications with Python Turtle

Now that we have a clear roadmap ahead let’s delve into each topic in detail and uncover the possibilities of Python Turtle.

Introduction to Python Turtle and its Features

Python Turtle is a beginner-friendly library that offers an interactive environment for learning and creating graphics. It provides a canvas on which the turtle can move and draw, allowing users to visualize the execution of their code in real time. Here are some key features of Python Turtle:

  • Simple and intuitive: Python Turtle is designed to be easy to understand and use, making it ideal for beginners.
  • Graphics and animation: With Turtle, you can create colorful shapes, patterns, and animations using a few lines of code.
  • Interactive learning: Turtle encourages experimentation and hands-on learning, enabling users to explore programming concepts in a visual and engaging manner.
  • Cross-platform compatibility: Python Turtle is available on multiple platforms, including Windows, macOS, and Linux, ensuring accessibility for all users.

Now that we have a brief overview of Python Turtle and its features let’s dive into the world of Turtle graphics and discover its capabilities.

Basic Turtle Movements and Commands

To start creating graphics with Python Turtle, we need to understand some basic movements and commands. The turtle can be controlled using a set of simple instructions, such as moving forward, turning left or right, and lifting or lowering the pen. Here are a few essential commands:

  • forward(distance): Moves the turtle forward by the specified distance.
  • backward(distance): Moves the turtle backwards by the specified distance.
  • left(angle): Rotates the turtle counter-clockwise by the given angle.
  • right(angle): Rotates the turtle clockwise by the given angle.
  • penup(): Lifts the pen so the turtle’s movements do not leave any marks.
  • pendown(): Lowers the pen, allowing the turtle to draw while moving.
  • speed(speed): Sets the speed of the turtle’s movements (0 is the fastest, 1 is the slowest).

Here are code examples demonstrating each of the basic commands of Python Turtle:

1. forward(distance): Moves the turtle forward by the specified distance.

forward distance output

In the above code, we create a turtle object and use the forward() method to move the turtle forward by 100 units.

2. backward(distance): Moves the turtle backwards by the specified distance.

backward distance output

Here, the turtle moves backwards by 100 units using the backward() method.

3. left(angle): Rotates the turtle counter-clockwise by the given angle.

left angle output

The turtle rotates 90 degrees in the counter-clockwise direction using the left() method.

4. right(angle): Rotates the turtle clockwise by the given angle

right angle output

In this example, the turtle rotates 90 degrees in the clockwise direction using the right() method.

5. penup(): Lifts the pen so the turtle’s movements do not leave any marks.

penup output

Here, the penup() method is called before moving the turtle forward by 100 units. Since the pen is up, no marks are left on the screen.

6. pendown(): Lowers the pen, allowing the turtle to draw while moving.

pendown output

In this code, the pendown() method is called before moving the turtle forward by 100 units. The pen is lowered, and the turtle’s movement leaves a visible line on the screen.

7. speed(speed): Sets the speed of the turtle’s movements (0 is the fastest, one is the slowest).

speed output

In this example, we set the turtle’s speed to 0, which is the fastest. The turtle moves forward by 100 units at the specified speed.

These code examples demonstrate the usage of each basic command in Python Turtle. You can modify the parameters and experiment with different values to see their effects on the turtle’s movements and drawings.

Let’s put these commands into action and create our first Turtle graphic: a square.

Turtle graphic output

In the above example, we import the turtle module and create a turtle object named my_turtle. We then use a loop to move the turtle forward by 100 units and turn left by 90 degrees four times, creating a square. Finally, we call turtle. done() to exit the turtle graphics window.

Drawing Shapes and Patterns with Python Turtle

With a basic understanding of Turtle movements and commands, we can now explore drawing more complex shapes and patterns. Turtle provides various methods to draw common shapes, such as circles, triangles, and polygons. Additionally, we can utilize loops and conditionals to create intricate designs and repetitive patterns.

Let’s illustrate this with an example of drawing a colorful circle pattern:

Drawing Shapes and Patterns output

In the above code, we create a turtle object and set the pen size to 3. We define a list of colors and use a loop to draw a circle with a radius of 100 units. Each time the loop iterates, the pen color is changed based on the current index in the color list. By adjusting the angle of rotation, we create a colorful circle pattern.

Using Loops and Conditionals for More Complex Designs

To create more intricate Turtle graphics, we can leverage loops and conditionals to generate repetitive patterns and designs. By combining different shapes, colors, and movements, we can create stunning visuals using code alone.

Let’s explore an example of drawing a spiral pattern:

Loops and Conditionals output

In the above code, we create a turtle object and set the pen size to 2 and speed to 0 (the fastest). We use nested loops to draw a square shape four times, and after each square, we rotate the turtle by 10 degrees. By repeating this process 36 times, we create a captivating spiral pattern.

Customizing Colors, Pen Size, and Speed

Python Turtle allows us to customize the appearance and behavior of the turtle graphics. We can change the pen color, size, and speed to create visually appealing designs. Here’s an example that demonstrates these customizations:

Customizing Colors output

In this example, we set the pen size to 4 and the speed to 1. We change the pen color to red using the pencolor() method before drawing a square. Then, we changed the pen color to blue and drew a circle using the circle() method. By customizing the pen color, size, and speed, we can create unique and visually appealing Turtle graphics.

Saving and Sharing Your Turtle Graphics

Python Turtle provides the functionality to save your Turtle graphics as image files. This allows you to share your creations with others or use them in various projects. To save a Turtle graphic, you can use the turtle. getscreen().getcanvas().postscript(file=”filename.eps”) command, replacing “filename.eps” with the desired name of the file and its extension.

Here’s an example that demonstrates how to save a Turtle graphic:

Saving-and-Sharing-output

In the above code, we draw a square using Turtle graphics. We then use the postscript() method to save the Turtle graphic as an EPS file named “my_square.eps”. You can replace the filename with your preferred name and choose a different file extension if desired.

Fun Projects and Creative Applications with Python Turtle

Python Turtle is not just limited to drawing shapes and patterns. It can be used to create interactive games, simulations, and even art. The only limit is your imagination! Here are a few ideas for fun projects and creative applications using Python Turtle:

1. Create a simple game like Pong or Snake using Turtle graphics.

2. Simulate natural phenomena such as the movement of planets or the behavior of a bouncing ball.

3. Draw intricate geometric designs using loops and mathematical formulas.

4. Design personalized greeting cards or artwork with colorful patterns and shapes.

5. Develop an educational tool to teach concepts like angles, geometry, or even music.

In this blog, we embarked on a journey to explore Python Turtle—a powerful and beginner-friendly library for creating graphics and learning programming concepts. We learned about the basics of Turtle movements and commands, drew shapes and patterns, and customized our graphics using colors, pen size, and speed. We also discovered how to save our Turtle graphics and explored fun projects and creative applications.

Python Turtle opens up a world of possibilities for beginners to express their creativity through coding. With its simplicity and visual feedback, it provides an engaging platform for learning and experimentation. So, unleash your imagination, pick up your virtual pen, and start creating amazing Turtle graphics with Python!

Remember, the more you practice and experiment, the more you’ll uncover the endless possibilities of Python Turtle. Happy coding!

You give me 15 seconds I promise you best tutorials Please share your happy experience on Google | Facebook

Tags: Features of Python Introduction to Python Turtle Learn Python python turtle python turtle for beginners

2 Responses

  • Pingbacks 0

Thank you very much for this tutorial. as I’m engaging myself to new possibilities it looks simple clear that this website has a lot to offer. This is my first time to this site and going through it step by step thankyou

A very useful tutorial. Thank you very much!

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

courses

python turtle assignment

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 4.1 Hello Little Turtles!
  • 4.2 Our First Turtle Program
  • 4.3 Instances — A Herd of Turtles
  • 4.4 The for Loop
  • 4.5 Flow of Execution of the for Loop
  • 4.6 Iteration Simplifies our Turtle Program
  • 4.7 The range Function
  • 4.8 A Few More turtle Methods and Observations
  • 4.9 Summary of Turtle Methods
  • 4.10 Glossary
  • 4.11 Exercises
  • 4. Python Turtle Graphics" data-toggle="tooltip">
  • 4.2. Our First Turtle Program' data-toggle="tooltip" >

4.1. Hello Little Turtles! ¶

There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform complex mathematical calculations. In this chapter we will introduce a module that allows us to create a data object called a turtle that can be used to draw pictures.

Turtle graphics, as it is known, is based on a very simple metaphor. Imagine that you have a turtle that understands English. You can tell your turtle to do simple commands such as go forward and turn right. As the turtle moves around, if its tail is down touching the ground, it will draw a line (leave a trail behind) as it moves. If you tell your turtle to lift up its tail it can still move around but will not leave a trail. As you will see, you can make some pretty amazing drawings with this simple capability.

The turtles are fun, but the real purpose of the chapter is to teach ourselves a little more Python and to develop our theme of computational thinking , or thinking like a computer scientist . Most of the Python covered here will be explored in more depth later.

Python Turtle Graphics

In this Python Turtle tutorial, we will learn How to make turtle graphics in Python turtle and we will also cover different examples related to turtle graphics. And, we will cover these topics.

  • Python turtle graphics tutorial
  • Python turtle graphics code
  • Python turtle graphics example
  • Python turtle graphics bar graph
  • Python turtle graphics online compiler
  • Python turtle graphics project

Table of Contents

In this section, we will learn about how to make turtle graphics in Python turtle.

Before moving forward we should have a piece of knowledge about graphics. Graphics are used to give a presentation or we can say that graphics is an image, drawing, design, or representing an object. Graphics are in conflict with text. The use of graphics looks our presentation attractive.

In the following code, we import turtle module import turtle for making turtle graphics which is shown on the screen after completion.

  • The turtle() method is used to make objects.
  • tur.penup() is used to pick up the turtle pen.
  • tur.pensize(10) is used to give the size to the pen.
  • tur.pencolor(“cyan”) is used to give the color to the pen.
  • tur.forward(100) is used to move the turtle in the forwarding direction.
  • tur.backward(100) is used to move the turtle in the backward direction.
  • tur.right(90) is used to move the turtle in the right direction.
  • tur.left(90) is used to move the turtle in the left direction.

After running the above code we get the following output in which we can see the letter E is drawn with the use of graphics.

Read: Python Turtle Art – How to draw

In this section, we will learn about the turtle graphics code in the turtle python.

Graphics are used to give an attractive look to our application where users feel Interested to work on the console and with help of graphics we animate the text and images to our console.

In the following code, we import turtle library import turtle . The turtle() method is used to make objects.

We are using the right() and forward() functions to give graphic shapes and these functions help to define an attractive look.

In the following output, we can see the graphic shape where with the help of forward() and right() used with help of loop to give this shape.

Read: Python Turtle Write Function

In this section, we will learn about graphics examples in Python turtle.

As we know graphics is used to give the attractive look to our application. We use graphics to give design to our text, shapes, images which gives a beautiful look to our window.

In the following code, we import the turtle module from turtle import *, import turtle. The turtle() method is used to make objects.

  • turt.forward(50) is used to move the turtle in the forward direction.
  • turt.right(90) is used to move the turtle in the right direction.

In the following output, we have designed a symbol notation using the forward() and right() functions.

Read: Python Turtle Speed With Examples

In this section, we will learn about turtle graphics bar graph in python turtle.

A bar graph is a graph that represents the data is drawn in the form of rectangular bars. Graphics bar graph looks attractive which attracts the people and represents its data in an attractive manner.

In the following code, we import the turtle module from turtle import * , import turtle for making a graphics bar graph.

  • tur.begin_fill() is used for starting filling colors.
  • tur.forward(heig) is used to move the turtle in the forward direction.
  • tur.end_fill() is used to stop filling the shape.
  • turtle.Screen() is used to make a screen for graphics.

After running the above code, we get the following output in which we can see the graphics bar graph is shown on the screen.

Python turtle graphics bar graph

Also, check: Python Turtle Colors + Examples

In this section, we will learn about graphics online compiler in Python turtle.

We use an online compiler for graphics we use a replit online compiler for graphics and give attractive to our application.

In replit, we can host our app and run out code on a server that we can access from anywhere.

In this, Link , we can see how our code is working on the Replit Platform and we can access that to see the output.

In the following code, we will learn about the turtle module import turtle .

  • tur.penup() is used to pick up the pen.
  • tur.fillcolor(clr) is used to fill the color.
  • tur.circle(Size) is used to draw the circle shape.

After running the above code we get the following output in which we can see the graphics are run on an online compiler.

Python turtle graphics online compiler

Read: Python Turtle Font

In this section, we will learn about the turtle graphics project in Python turtle.

Before moving forward we should have a piece of knowledge about a graphics project. Graphics are used for giving the look to our application. In this project, we draw rainbow benzene with the help of a turtle from which our screen gives an attractive look to the user.

In the following code, we will import the turtle module from turtle import * , import turtle . The turtle() method is used to make objects.

  • turtle.bgcolor(‘black’) is used to give the background color to screen.
  • tur.pencolor(colrs[i%6]) is used to give the pencolor to pen.
  • tur.width(i//100 + 1) is used to give the width to pen.
  • tur.forward(i) is used to move the turtle in the forward direction.
  • tur.left(59) is used to move the turtle in left direction.

After running the above code, we get the following output in which we can see the rainbow benzene is drawn on the screen.

You may also like to read the following tutorials.

  • Python Turtle Size – Detailed Guide
  • Python Turtle Square – Helpful Guide
  • Python Turtle Triangle + Examples
  • Fractal Python Turtle + Examples
  • Python Screen Capture
  • Python Turtle Tracer – How to use

So, in this tutorial, we will discuss Python turtle graphics and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.

Bijay - Python Expert

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile .

101 Computing

More results...

  • View all quizzes
  • GCSE Concepts & Quizzes
  • A Level Concepts & Quizzes
  • Little Man Computer (LMC)
  • Computer Networks
  • Database Concepts
  • Cryptography
  • All Python Challenges
  • Python Challenges – Beginner
  • Python Challenges – Intermediate
  • Python Challenges – Advanced
  • HTML, CSS & JavaScript
  • BBC micro:bit
  • OCR J277/01 – 1.1 System Architecture
  • OCR J277/01 – 1.2 Memory and Storage
  • OCR J277/01 – 1.3 Computer networks
  • OCR J277/01 – 1.4 Network security
  • OCR J277/01 – 1.5 – Systems software
  • OCR J277/01 – 1.6 – Ethical, legal, cultural and environmental impacts of digital technology
  • OCR J277/02 – 2.1 – Algorithms
  • OCR J277/02 – 2.2 – Programming fundamentals
  • OCR J277/02 – 2.3 – Producing robust programs
  • OCR J277/02 – 2.4 – Boolean logic
  • OCR J277/02 – 2.5 – Programming languages and Integrated Development Environments
  • OCR H446/01 – 1.1 The characteristics of contemporary processors, input, output and storage devices
  • OCR H446/01 – 1.2 Software and software development
  • OCR H446/01 – 1.3 Exchanging data
  • OCR H446/01 – 1.4 Data types, data structures and algorithms
  • OCR H446/01 – 1.5 Legal, moral, cultural and ethical issues
  • OCR H446/02 – 2.1 Elements of computational thinking
  • OCR H446/01 – 2.2 Problem solving and programming
  • OCR H446/02 – 2.3 Algorithms
  • 101 Extra Python Challenges
  • 101 Python Challenges
  • 101 Computing Challenges
  • Become a member!
  • Your Account
  • Solved Challenges
  • Membership FAQ

Python Turtle – Iteration

Let’s recap.

In our previous challenge , we looked at using sequencing to write a program using Python Turtle to complete a drawing.

Remember when using Python Turtle, the most useful instrcutions are as follows:

  • myPen.color(“red”)
  • myPen.forward(100)
  • myPen.right(90)
  • myPen.left(45)
  • myPen.penup()
  • myPen.pendown()
  • myPen.goto(0,0)
  • myPen.circle(50)

Learning Objectives: In this challenge we are going to use for loops to repeat a set of instructions many times. This is called iteration . We are also going to look at nested loops . (A loop within a loop) Challenge: By using a loop you can repeat a set of instructions many times. This is called iteration . Look at the following scripts: Can you create your own script using iteration?

Did you like this challenge?

Click on a star to rate it!

Average rating 3.5 / 5. Vote count: 19

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Other challenges you may enjoy...

medieval-castle

Recent Posts

  • Circular Maze Challenge
  • Pronic Numbers Challenge
  • Olympics Host Cities (CSV Challenge)
  • Paris 2024 – JSON Challenge
  • Online Python IDE
  • Space Explorer: The Way Back Home
  • The Lost Treasures of Pirate Island
  • Cryptic Puzzles – Computer Networks
  • Computer Science – Cryptic Crossword #02
  • Ice Cream Price Calculator
  • View more recent posts...
  • View all our challenges...
  • Take a Quiz...

LMC Simulator

Our Latest Book

python turtle assignment

  • Computing Concepts
  • Python Challenges
  • Privacy Policy
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Python Turtle Drawing Assignment - Trouble with assigning variables

I have an assignment due in a few hours and I'm stuck as to what to do. I am using python 3.

I keep trying to run the code, but I get errors. At this point I figured I'd ask for help.

Thank you in Advance!

Instructions: http://people.uncw.edu/cferner/Classes/csc231/Assignment1.html

Download link for Python file

  • turtle-graphics

Phillip Ward's user avatar

  • Could you also post the errors –  thesonyman101 Commented May 24, 2017 at 23:41
  • Cool looking at it right now –  thesonyman101 Commented May 24, 2017 at 23:45
  • Appreciate it!! –  Phillip Ward Commented May 24, 2017 at 23:45
  • 2 the fact that the assignment asks that you name mangle to 'make the data private' is mind boggling –  ryugie Commented May 24, 2017 at 23:46
  • It's either pasting your code here and formatting problem or your Python code is not properly formatted at all. –  errata Commented May 24, 2017 at 23:47

2 Answers 2

Your testing code is a mess, you don't need multiple turtles, just one, something along the lines:

This should bring you to step 7 in your instructions.

I don't know what your __var__() function is supposed to do, it seems like a lengthy no-op. Your draw() function slightly tweaked:

cdlane's user avatar

The problem is the code you pasted in the post is not the same as in the file you list. In the file you have an error on line 92 where you don't supply any args to setColor:

schaabs's user avatar

  • 1 Thanks for the input! I think the indentation was just a formatting error, but I posted the download link for the file at the bottom of the post if you wouldn't mind taking a look. –  Phillip Ward Commented May 24, 2017 at 23:57
  • the code you pasted above isn't the same as the code in the file –  schaabs Commented May 25, 2017 at 0:01
  • in the file your first call has no args: for i in [phil, macie, sashi, roxie, darla, sammy]: mr.setColor() mr.setX(xy) –  schaabs Commented May 25, 2017 at 0:02
  • I changed it to "mr.setColor(c)". I need to call the "draw" function from line 53ish under the for loop. However I get this error: mr.draw(self,turtle) NameError: name 'self' is not defined –  Phillip Ward Commented May 25, 2017 at 0:08

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python variables turtle-graphics or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Empty Poincare Section When The Phase Space Is Full
  • ESTA is not letting me pay
  • using chapter style in latex (book)
  • What is this device in my ceiling making out of battery chirps?
  • siunitx \micro font problem
  • Indicator function necessary for independence from filtration?
  • Maximizing the common value of both sides of an equation
  • Fast algorithm to obtain an orthogonal vector to a set of vectors
  • How to define a function for Schmitt trigger?
  • Reference for proof about a result concerning Sobolev spaces and exponential growth
  • In Top, *how* do conjugate homorphisms of groups induce homotopies of classifying maps?
  • Showing analytically that sampling exactly 1 period of a sinusoid yields a spectrum with no lobes in the DFT
  • What unique phenomena would be observed in a system around a hypervelocity star?
  • In 1982 Admiral Grace Hopper said "I still haven't found out why helicopter rotors go the way they do". If she were here today, how might one answer?
  • Could an alien pathogen actually have an effect on us?
  • Replacing aircon capacitor, using off brand same spec vs lower/higher spec from correct brand?
  • How to frame certain cells with tabular?
  • Explain how π – 1 + 50 + ⅔ × 1000 is PLONK
  • How did Oswald Mosley escape treason charges?
  • Jewelry and adornment
  • Does it pay to put effort in fixing this problem or better reinstall Ubuntu 24.04 from scratch?
  • Is 3 ohm resistance value of a PCB fuse reasonable?
  • What is the highest apogee of a satellite in Earth orbit?
  • How much time would an astronaut experience accelerating to .9999x the speed of light at an acceleration of 1G from the astronauts perspective?

python turtle assignment

Get the Reddit app

Subreddit for posting questions and asking for general advice about your python code.

Python turtle assignment

I had posted up the wrong assignment. The one I posted was for later on, this ones actually the one due in a few days. This one has to do with functions and turtles, which I have been trying for a bit of time now. I’m having some difficulty with this program, functions are a weak point for me, this assignment wants the user to be able to pick out of three options, one of them being to draw a rectangle, the other a circle, and the last option is to simply quit.

Upon picking one of the options, let’s say rectangle. It will prompt the user to input a x,y cord, so where the turtle will be placed. The length and width with the turtle turning left 90° so it can complete the rectangle with what’s inputted.

The circle option will do something similar, just with the circle.

The quit option will close the program.

It will loop until they pick a proper option.

I’m having an issue executing this, I’ll post the code I have at the moment as a response to this post.

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

CopyAssignment

We are Python language experts, a community to solve Python problems, we are a 1.2 Million community on Instagram, now here to help with our blogs.

  • I Love You Program In Python Turtle

I Love You Program In Python Turtle

Introduction

Hello and welcome to the  copyassignment , today we will learn how to write the I Love You Program In Python Turtle. This could be very interesting for both beginners and experienced coders to learn. This could be simple and easy to understand because we have explained the code in simple terms.

Click here if you want to only copy the code for the I Love You Program In Python Turtle.

We have one similar article, there, we have explained How to write I Love You In Coding languages . We recommend you to visit that article as well.

Now, let’s start coding for the I Love You In Python Turtle.

Step 1: Importing Turtle Librar y

Step 2: creating a cursor and a separate canvas, step 3: creating a heart background for the i love you program in python turtle, step 4: creating a function to draw the left curve of our heart background, step 5: creating a function to write “i” inside our heart background, step 6: creating a function to write “love” inside our heart background, step 7: creating a function to write “you” inside our heart background, step 8: creating a pause function to pause a cursor at the end of the i love you program in python turtle, step 9: changing the start position of our cursor, step 10: setting up the configuration of the cursor and calling all the required function, complete code for i love you program in python turtle.

I Love You Program In Python Turtle

Video Output:

Our code is complete, and we finally run it to see the I Love You written with Python Turtle.

We hope this article on the I Love You Program In Python Turtle Library Helps you.

Thank you for reading this article,  click here  to start learning Python in 2022.

  • Radha Krishna using Python Turtle
  • Drawing letter A using Python Turtle
  • Wishing Happy New Year 2023 in Python Turtle
  • Snake and Ladder Game in Python
  • Draw Goku in Python Turtle
  • Draw Mickey Mouse in Python Turtle
  • Happy Diwali in Python Turtle
  • Draw Halloween in Python Turtle
  • Write Happy Halloween in Python Turtle
  • Draw Happy Diwali in Python Turtle
  • Extract Audio from Video using Python
  • Drawing Application in Python Tkinter
  • Draw Flag of USA using Python Turtle
  • Draw Iron Man Face with Python Turtle: Tony Stark Face
  • Draw TikTok Logo with Python Turtle
  • Draw Instagram Logo using Python Turtle
  • I Love You Text in ASCII Art
  • Python Turtle Shapes- Square, Rectangle, Circle
  • Python Turtle Commands and All Methods
  • Happy Birthday Python Program In Turtle
  • Draw Python Logo in Python Turtle
  • Space Invaders game using Python
  • Draw Google Drive Logo Using Python
  • Draw Instagram Reel Logo Using Python
  • Draw The Spotify Logo in Python Turtle
  • Draw The CRED Logo Using Python Turtle
  • Draw Javascript Logo using Python Turtle
  • Draw Dell Logo using Python Turtle
  • Draw Spider web using Python Turtle

' src=

Author: Ayush Purawr

python turtle assignment

Search….

python turtle assignment

Machine Learning

Data Structures and Algorithms(Python)

Python Turtle

Games with Python

All Blogs On-Site

Python Compiler(Interpreter)

Online Java Editor

Online C++ Editor

Online C Editor

All Editors

Services(Freelancing)

Recent Posts

  • Most Underrated Database Trick | Life-Saving SQL Command
  • Python List Methods
  • Top 5 Free HTML Resume Templates in 2024 | With Source Code
  • How to See Connected Wi-Fi Passwords in Windows?
  • 2023 Merry Christmas using Python Turtle

© Copyright 2019-2024 www.copyassignment.com. All rights reserved. Developed by copyassignment

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Create a Snake-Game using Turtle in Python

A snake game is an arcade maze game which has been developed by Gremlin Industries and published by Sega in October 1976. It is considered to be a skillful game and has been popularized among people for generations. The snake in the Snake game is controlled using the four direction buttons relative to the direction it is headed in. The player’s objective in the game is to achieve maximum points as possible by collecting food or fruits. The player loses once the snake hits the wall or hits itself.

For the python beginners, those who are interested in making something easier in your domain can definitely try this out and the module Turtle was made exactly for this purpose for the beginners to try out and can also submit as a part of the project. This program will be done in Python 3 .

So, we will be creating a Python-based-game using the following modules:

  • Turtle: It is a pre-installed python library that enables users to create shapes and pictures by providing them with a virtual canvas.
  • Time: This function is used to count the number of seconds elapsed since the epoch.
  • Random: This function is used to generate random numbers in Python by using random module.

The following code can be easily done using PyCharm application which is specially made for Python programs.

Also, VSCode can be used for this program. Install Python3 from extensions of VSCode. Then, save the program in the form of your_filename.py

Below is the step-by-step Approach to create a Snake Game using Turtle module:

Step 1 : We will be importing modules into the program and giving default values for the game.

Step 2 : Now, we will be creating the display of the game, i.e, the window screen for the game where we will create the head of the snake and food for the snake in the game and displaying the scores at the header of the game.

python turtle assignment

The initial score as the header, white: snake’s head, red: fruit

Step 3 : Now, we will be validating the key for the snake’s movements. By clicking the keywords normally used for gaming ‘w’, ‘a’, ‘s’ and ‘d’, we can operate the snake’s movements around the screen.

Step 4 : Now, lastly, we will create the gameplay where the following will be happening:

  • The snake will grow its body when the snake eats the fruits.
  • Giving color to the snake’s tail.
  • After the fruit is eaten, the score will be counted.
  • Checking for the snake’s head collisions with the body or the wall of the window screen.
  • Restarting the game automatically from the start after the collision.
  • The new shape and color of the fruit will be introduced every time the window is restarted.
  • The score will be returned to zero and a high score will be retained until the window is not closed.

Below the complete program based on the above approach:

Code Explanation:

  • The code starts by creating a window screen.
  • The title of the window is “Snake Game”.
  • The background color of the window is blue.
  • Next, the code creates two turtle objects: head and food.
  • Head is used to control the snake, while food will be used as the game’s object.
  • The code first sets up head so that it looks like a square with white color and starts at (0, 0).
  • Next, it sets up food so that it looks like a square with blue color and places it at (10, 10).
  • Finally, head moves towards food using direction=”Stop”.
  • The code creates a window screen with the title “Snake Game” and sets the background color to blue.
  • Next, a square head object is created and set to have the color white.
  • The pen up() method is called on the head object, which causes it to rise up from the bottom of the screen.
  • Finally, the goTo() method is used to move the head object towards (0, 0) in the x-direction.
  • Next, two turtle objects are created – one for food and one for head.
  • The food object has a shape of “square” and will be placed at (0, 0) on the screen.
  • The head object has no shape specified and will be placed at (0, 0) in the y-direction
  • The code starts by creating a few variables to store information about the game.
  • The first is food, which stores information about the shapes and colors of the food that will be displayed on the screen.
  • Next, the code creates a function called speed() that will control how quickly the food moves across the screen.
  • Finally, the shape() and color() functions are used to create different types of food (square, triangle, and circle) with corresponding colors and speeds.
  • The next section of code sets up an event handler for when the user clicks on one of the buttons in the toolbar.
  • This handler calls a function called goto() that takes two arguments: position (in pixels) and direction (which can be “up”, “down”, “left”, or “right”).
  • goTo() then uses these values to move the pen object to a specific location onscreen and set its properties accordingly.
  • The last section of code displays some text onscreen and starts timing it using time().
  • Then it prints out a score value for each round played as well as high scores for both players at once.
  • The code will create a turtle that will move at 0 speed and have a square shape.
  • The turtle will be white in color and will start at the top left corner of the screen.
  • Once the code has executed, it will output “Score : 0 High Score : 0” in center alignment.
  • The code starts by creating three variables: head, wn, and godown.
  • The head variable stores information about the player’s current position on the screen (xcor and ycor), while wn is a listening object that will be used to track keyboard input.
  • Godown stores information about where the player should go next (if they are moving left or right), and goleft and goright store key directions for moving up, down, or left/right respectively.
  • The code then starts to loop through each of these variables in turn.
  • If any of them change (head.direction, wn.listen(), godown.direction), the code updates itself accordingly and sets various properties on head such as its xcor and ycor coordinates, its heading direction (up, down, left/right), as well as colors and shapes for each segment in the game world according to what was just inputted by the user via keyboard presses.
  • Finally, there is a delay timer set to 0.1 seconds which allows time for one frame of animation before starting over again with another round of gameplay; this is important because it ensures that everything looks smooth even when there are lots of objects moving around on-screen at once!
  • The code assigns key directions to the turtle, listens for user input, updates the screen and calculates the player’s score.
  • It also creates a new square segment if needed and moves it according to the key presses.
  • If the player is moving their turtle up or down, then head.direction will be set to “up” or “down”, respectively.
  • If they are moving left or right, head.direction will be set to “left” or “right”.
  • The code also checks whether the player’s current position falls within a food zone and if not, then the appropriate x and y coordinates are randomly generated and stored in food and moved accordingly by calling Turtle().goto() with those values.

Please Login to comment...

Similar reads.

  • Python-turtle
  • Technical Scripter 2020
  • How to Delete Discord Servers: Step by Step Guide
  • Google increases YouTube Premium price in India: Check our the latest plans
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Improving the Turtle library

I’m a big fan of the turtle module (to the point where MarieRoald and I created a library to make embroidery patterns with turtle commands: https://turtlethread.com/ ), and I have used turtle.py several times in introductory Python courses. However, the more I’ve used it, the more I notice features that I wish were present.

Here is a list of the main features I’m missing and that I’ve found other educators miss as well.

  • begin_fill / end_fill
  • begin_poly / end_poly
  • turtle.tracer(0) / turtle.update(); turtle.tracer(1) (An easy way to disable automatic canvas updates)
  • penup / pendown (might be fixed with the new teleport method)
  • color , pencolor , fillcolor

An easy way to save drawings

  • Decoupling turtle.py from Tkinter (big change)

At the end of this post, I have also listed some oddities and (potential) bugs that Marie and I have found working on this.

The Utility

Context managers for begin/end-functions.

I’ve typically used Turtle to introduce variables, loops and functions. However, when we move on to context managers, I can no longer use turtle. So I’ll have to teach learners to close their files after opening them and also what a context manager is at the same time. It would be extremely useful to demonstrate context managers with Turtle so I only have to explain one concept at a time.

Filling polygons are particularly well suited for this! You always need to call begin_fill and end_fill , which would be the perfect visual demonstration of what context managers do.

Unfortunately, Turtle doesn’t work this way, so I’ll have to resolve to hand-waving about context managers while also explaining file-opening – and whenever someone asks, “Why don’t we have this in Turtle?” (I’ve been asked on more than one occasion), I don’t have any good answer.

As an addendum to this, I would love a context manager for disabling auto-update that resets and updates the screen once exited.

Example code:

Context managers for other utilities

Really the same as above. However, for the three cases above, we already follow the setup-teardown pattern manually. For penup / pendown , color , pencolor , fillcolor and pensize , we don’t explicitly follow this pattern in the same way. However, we still do often want to change colour, pen size, etc temporarilly.

The turtle library supports saving the drawings as postscript files by calling the cryptic command turtle.getscreen().getcanvas().postscript(file=filename) . Whenever a learner asks “How can I print what I made?”, I’ll have to show them that extremely scary command with method chaining - not the best snippet to show someone who’s still struggling with functions…

If we instead had a turtle.save(filename, format="postscript") , or maybe a turtle.getscreen().save(filename) , then I could tell the learners to use that function and an online postscript to pdf converter instead.

An easy way to disable auto-updating the canvas

The Turtle library quickly becomes slow if you want to draw complex drawings, which leads some learners to find the cryptic turtle.tracer(0) command. This command disables automatically updating the canvas, and lets the learner draw many lines at once by calling turtle.update() . This is a must-have for anyone that uses turtle for anything a bit complicated.

Unfortunately, explaining why you write turtle.tracer(0) is not something I have managed in a good way, and I think it would be much easier to tell my learners to use something like “turtle.disable_autoupdate()” instead of turtle.tracer(0) .

Decoupling turtle.py from Tkinter

turtle.py is tightly coupled with tkinter. In fact, you cannot even import the turtle module if you have a Python version built without Tkinter. In an ideal world, we would have a general Turtle API in Python where anyone can implement their own backend on top of it. This could enable fully compatible turtle interfaces across various platforms that currently don’t support Tkinter (like PyScript), saving the canvas as something other than a postscript file and more.

There are also several reasons for why I would like to import Turtle on systems without Tkinter both in TurtleThread and elsewhere. In TurtleThread, we inherit from the TNavigator class from the Turtle module. However, we also want it to be possible to run TurtleThread on a web server without Tkinter installed. To facilitate this, we had to copy the TNavigator class into a separate file. We also have some visualisation code that we use Xvfb to test, and it would be great if we could switch out the turtle-type with something that doesn’t draw on a Tkinter canvas.

Marie Roald and I spent some time on PyCon US 2024 trying to figure out how to do this without breaking backwards compatibility and we have since then tried to assemble our thoughts.

Thoughts on how to decouple turtle.py from Tkinter

Some observations about the current api (can be skipped).

  • The API is structured around two classes: A singleton Screen class that contains the Tkinter canvas and a Turtle object that is responsible for drawing on the screen.
  • Most of the user-facing API lies on the Turtle class. However, not everything – Screen.bgcolor being a notable exception.
  • The Screen object contains a ScrolledCanvas – a wrapper of the TKinter canvas that adds some extra functionality.
  • Methods of Turtle instances are forwarded to the Screen instance as drawing instructions and are immediately passed for Tkinter to be drawn during the next iteration of the GUI loop.
  • The code doesn’t follow the encapsulation principle: Whenever Turtle -instances do anything, they call Screen._incrementudc (increment update counter) before checking if the screen should be updated. If so, then the command is passed to the screen. This introduces a bug shown below.
  • Multiple turtles can draw on the same screen, but they can only write to one screen at a time
  • The tight coupling between the “logical drawing” and the GUI window means that we need a larger rewrite of the turtle module if we want to support other backends.
  • Some methods are duplicated with the same name but have different behaviours for turtles and the screen. An example is onscreenclick , which records when the turtle shape is pressed for turtle instances and when the turtle canvas is clicked for the screen instance.

The proposed API

We propose to define an official Turtle interface in a backend-agnostic way. Implementors of new Turtle backends (e.g. for WASM-builds of CPython, Jupyter notebooks or image exporters) can then all agree on how to implement Turtle renderers and what they should include (outside the minimal requirements).

Specifically, we propose to define three main classes: Turtle , Canvas and Renderer . Each turtle draws on exactly one canvas (stored as an immutable variable), and the canvas has a list of turtles that have drawn on it. Whenever a command is passed to a turtle, it forwards it to the Canvas, which stores a programmatic list of them. Then, if the canvas’ current update counter is zero, it forwards the commands to the renderers.

The renderers must be able to do the following:

  • Draw straight lines (remember, circles are polygons in turtle)
  • Undo drawing a line
  • Draw filled polygons
  • Draw polygonal vector “stamps”
  • Set the background colour

The renderers can also do the following

  • Draw custom “stamps” (e.g. raster images)
  • Do live updates of the drawing
  • Support interactivity such as onclick.
  • Support interactive events for clicking the shape of a single turtle.

However, this architecture is not compatible with the current state of affairs. Therefore, to ensure backward compatibility, we can also include a Screen class, which is a wrapper of both a canvas and a renderer (maybe the renderer type can be controlled with an environment variable?).

Oddities, bugs and potential bugs

The turtle.tracer -bug.

Run the following code:

There are two oddities here, one of which is definitely a bug.

  • Potential bug: The colour of the screen is immediately updated as only turtle instances check if the screen is supposed to be updated
  • Bug: Both espen and gard have moved, but only gard made a line on the screen.

The Terminator exception

Run the following code

By reading this code, you’d think that you first get one turtle drawing and once you close it, you’ll get a second turtle drawing. However, this is not the case. You’ll get a turtle.Terminator exception instead as the singleton Screen -object is closed. I’ve seen people mistakenly saying that calling turtle.bye will fix this, but that is not the case – it will only trigger the turtle.Terminator exception again. I have two solutions:

or by manually modifying “private” variables:

neither are good solutions in an intro to Python class.

This bug has been a big headache during teaching since this bug will trigger for anyone that use an interactive coding environment like Spyder .

Undo quircks

Turtle-specific undo buffers.

Each turtle object has an undo-buffer, and calling turtle.undo() will undo the latest command by the global Turtle-instance, so if you have multiple turtles (e.g. inês and the global turtle -instance), then turtle.undo() might behave in surprising ways. Try, for example:

Confusing clone behaviour

We can also clone turtles, which is even more confusing!

Here, inês2 moves back to to (0, 0) while inês stays put at (100, 0). However, the line that inês drew disappeared!

Custom deque?

The undo -function implements its own circular buffer instead of using a deque . I cannot understand why, especially since (as far as I can tell) the deque was added before undo was added to turtle.py ?

Prior Discussion

I haven’t found any discussion on this online, but I mentioned it to some core team members and educators at PyCon US 2023 and PyCon US 2024 and received positive feedback – educators, in particular, seemed excited about the proposed changes. The main question was how functional changes to the turtle module would affect existing teaching materials and schools and universities that may be on older versions of Python.

While it could be confusing for learners in the beginning to see that Python code they find online doesn’t work on a school computer with an old Python version, I don’t think that alone is worth skipping these changes. Teaching materials change all the time, and I believe that these changes will bring more positive changes than negative.

Who will make these changes

Marie and I would be happy to attempt to make these changes. However, our free time is unfortunately very limited these days, so progress on the main rewrite will be slow if we lead the work on it.

My guess is to support the cumulate flag. You can still back it with a deque, looks like it saves a few lines:

I see lots of support and no objections to your ideas!

To get started, would you like to pick something smallish with high impact? (Perhaps the new save() method?) Each will need its own issue and PR. Instructions are in the devguide , but don’t hesitate to ask questions in the issue, this topic, or new topics here.

:turtle:

FYI, it looks like there’s a typo in the GitHub link. I believe the intended target is https://github.com/MarieRoald .

IMAGES

  1. Turtle Race Python Project: Complete Guide

    python turtle assignment

  2. Introduction to programming in Python with Turtle

    python turtle assignment

  3. The Beginner's Guide To Python Turtle

    python turtle assignment

  4. Python Turtle Cheat Sheet Version 1.2 PDF

    python turtle assignment

  5. Helpful Python Turtle Example

    python turtle assignment

  6. Beginners To Advanced Python Turtle Projects

    python turtle assignment

VIDEO

  1. Python Turtle Art

  2. graphics program using turtle in python #Turtle #python #graphics #programming #pythonturtle

  3. Assignment Turtle Graphics Program

  4. Turtle python #python #turtleprogramming #turtlepython #suscribete

  5. Mesmerizing Python Turtle Graphic Idea #python #programming #coding

  6. turtle python #python #turtleprogramming #turtlepython #practice

COMMENTS

  1. The Beginner's Guide to Python Turtle

    The Python turtle library comes with a similar interactive feature that gives new programmers a taste of what it's like to work with Python. In this tutorial, you will: Understand what the Python turtle library is; ... The assignment operator = is used to assign a value to something. To learn more about the differences between the two, ...

  2. turtle

    Introduction¶. Turtle graphics is an implementation of the popular geometric drawing tools introduced in Logo, developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.. Turtle star. Turtle can draw intricate shapes using programs that repeat simple moves. In Python, turtle graphics provides a representation of a physical "turtle" (a little robot with a pen) that draws on a ...

  3. Python Turtle Graphics Tutorial for Absolute Beginners

    Learn programming in Turtle, a Python Library, in this 2 minute tutorial for beginners. Playing around with the Turtle library is a great way to practise th...

  4. 4. Turtle Drawing Practice

    1. import turtle. 2. (practice_problems_1) For the first three problems, beginning your drawing from the of the square, then ending in the middle of the square (facing the same direction as you started) can be a really helpful strategy. You might want to create a function such as that does this. This new function could even call your old.

  5. 3. Hello, little turtles!

    Here are a couple of things we'll need to understand about this program. The first line tells Python to load a module named turtle . That module brings us two new types that we can use: the Turtle type, and the Screen type. The dot notation turtle.Turtle means "The Turtle type that is defined within the turtle module".

  6. The turtle library

    Assignment 17. Create a Python script named turtle_race.py which simulates a race between two turtles, a blue turtle and a green one. The first to move 200 forward would win the race. The race is turn by turn. In each turn both turtles roll a dice to determine how far they move forward.

  7. Turtle Programming in Python

    Plotting using Turtle. To make use of the turtle methods and functionalities, we need to import turtle."turtle" comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 4 steps: Import the turtle module. Create a turtle to control.

  8. Python Turtle Tutorial

    Turtle is a Python module that provides a drawing board like feature, which enables users to create pictures and shapes. Turtle is one of the most popular ways of introducing programming to kids and is part of the original LOGO programming language. The on-screen pen that is used for drawing is called the turtle and can be moved using the functions like turtle.forward(), turtle.left(), etc.

  9. 4. Python Turtle Graphics

    4.2 Our First Turtle Program; 4.3 Instances — A Herd of Turtles; 4.4 The for Loop; 4.5 Flow of Execution of the for Loop; 4.6 Iteration Simplifies our Turtle Program; 4.7 The range Function; 4.8 A Few More turtle Methods and Observations; 4.9 Summary of Turtle Methods; 4.10 Glossary; 4.11 Exercises

  10. Python Turtle for Beginners

    Python Turtle is a built-in library in Python that provides a fun and interactive way to learn programming concepts. It is based on the Logo programming language and allows users to draw graphics and shapes on a screen using a turtle metaphor. The turtle acts as a virtual pen, which can move, turn, and draw lines as instructed by the user. ...

  11. Python & Turtle: A Practical Guide for Beginners and Beyond

    The Python community has a set of guiding principles known as the Zen of Python. These principles emphasize the beauty of simplicity, readability, and elegance in code. Discover how embracing the ...

  12. 4.1. Hello Little Turtles!

    Hello Little Turtles! — How to Think like a Computer Scientist: Interactive Edition. 4.1. Hello Little Turtles! ¶. Activity: 4.1.1 YouTube (vid_turtleintro) There are many modules in Python that provide very powerful features that we can use in our own programs. Some of these can send email or fetch web pages. Others allow us to perform ...

  13. Beginners To Advanced Python Turtle Projects

    Turtle is a Python library for creating graphics, images, and games. It has a feature similar to a drawing board that allows users to draw pictures and shapes. Turtle programming is also known as LOGO programming. This library is widely recommended for someone who is getting started in design programming.

  14. Python Turtle Graphics

    Code: In the following code, we import the turtle module from turtle import *, import turtle for making a graphics bar graph. tur.begin_fill () is used for starting filling colors. tur.left (90) is used to move the turtle in the left direction. tur.forward (heig) is used to move the turtle in the forward direction.

  15. Python Turtle Tutorial

    Create a basic game with the python package 'turtle' with me! 🔔NEW videos, tutorials and projects EVERY week so subscribe and hit the bell button so you don...

  16. Python Turtle

    Let's Recap In our previous challenge, we looked at using sequencing to write a program using Python Turtle to complete a drawing. Remember when using Python Turtle, the most useful instrcutions are as follows: myPen.color("red") myPen.forward(100) myPen.right(90) myPen.left(45) myPen.penup() myPen.pendown() myPen.goto(0,0) myPen.circle(50) Learning Objectives: In this challenge we are going ...

  17. Draw any polygon in Turtle

    Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. turtle drawings are basically drawn using four methods defined in the turtle module. forward (x): moves the turtle (pen) in the forward direction by x unit.

  18. Python turtle assignment pleasehelp

    Python turtle assignment pleasehelp. Ask Question Asked 2 years, 6 months ago. Modified 2 years, 6 months ago. Viewed 389 times 1 I need to create a function called SpinPolygon that will do what the instruction says. I am a noob coder. SpinPolygon(Turtle, sides, angle, length, repeat): Draws the polygon number of times while turn polygon by the ...

  19. Python Turtle Drawing Assignment

    I have an assignment due in a few hours and I'm stuck as to what to do. I am using python 3. I keep trying to run the code, but I get errors. ... Python Turtle Drawing Assignment - Trouble with assigning variables. Ask Question Asked 7 years, 2 months ago. Modified 7 years, 2 months ago. Viewed 451 times

  20. Draw Circle in Python using Turtle

    Now to draw a circle using turtle, we will use a predefined function in "turtle". circle (radius): This function draws a circle of the given radius by taking the "turtle" position as the center. Example: Python3. import turtle. t = turtle.Turtle() r = 50.

  21. Python turtle assignment : r/learnpython

    Python turtle assignment . I had posted up the wrong assignment. The one I posted was for later on, this ones actually the one due in a few days. This one has to do with functions and turtles, which I have been trying for a bit of time now. I'm having some difficulty with this program, functions are a weak point for me, this assignment wants ...

  22. I Love You Program In Python Turtle

    Step 3: Creating a Heart Background for the I Love You Program In Python Turtle. # Method to draw a heart def draw_complete_heart (): # Set the fill color to #FF0000 my_turtle_cursor.fillcolor ("#FF0000") # Start filling the color my_turtle_cursor.begin_fill () # Draw the left line my_turtle_cursor.left (140) my_turtle_cursor.forward (294 ...

  23. Create a Snake-Game using Turtle in Python

    Then, save the program in the form of your_filename.py. Below is the step-by-step Approach to create a Snake Game using Turtle module: Step 1: We will be importing modules into the program and giving default values for the game. Python. import turtle import time import random delay = 0.1 score = 0 high_score = 0.

  24. Improving the Turtle library

    In fact, you cannot even import the turtle module if you have a Python version built without Tkinter. In an ideal world, we would have a general Turtle API in Python where anyone can implement their own backend on top of it. This could enable fully compatible turtle interfaces across various platforms that currently don't support Tkinter ...