Hello, I’m Yue Chuang.

The Python standard library includes the Turtle module, commonly known as Turtle Drawing, which provides simple drawing tools for drawing various graphics in standard application Windows.

The drawing method of the Turtle is very simple and intuitive, like a baby turtle with paint on its tail crawling across a computer screen, drawing lines as it moves. Using turtle drawings, we can create an impressive visual effect with just a few lines of code, and we can follow the turtle’s movement and see how each line of code affects its movement.

This helps us understand the logic of the code better. So turtle drawing is often used as a tool for beginners to learn Python.

Create a canvas

Let’s see how turtles work. First, we need to import the Turtle module. Then we will create a blank window as the canvas, the window size is 800 pixels wide and 800 pixels high. Then create a brush and set the shape of the cursor to a turtle. The code is as follows.

import turtle

window = turtle.Screen()
# turtle.setup(800, 800)
turtle.setup(width=800, height=800)
t = turtle.Pen()
turtle.shape("turtle") # The Shape of a Turtle
Copy the code

Running this code, we see a blank window with a small turtle in the middle, as shown in Figure 1.

The drawing area of the Turtle program window uses cartesian coordinates, which map the stage to a logical grid using a coordinate system consisting of X and Y coordinates.

We set the window size to be 800 pixels wide and 800 pixels high. The X-axis coordinates range from −400 to 400, and the Y-axis coordinates range from −400 to 400. The initial position of the turtle is in the center of the drawing area of the window (0,0), with the head facing the positive direction of the X-axis, as shown in figure 2.

Tip: A pixel is a dot on the screen, the smallest element that can be represented. Everything we see on a screen is made up of pixels.

Move the turtle

Next, we want the turtles to move. There are many commands to control the movement of a turtle. Let’s start with a simple command, using the forward() method to make a turtle move 100 pixels forward:

turtle.forward(100)
Copy the code
  • “Forward” is the command for the turtle to move forward, and 100 is the distance traveled.

  • The command to make the turtle move backward is backward, and the arguments in parentheses are the distance traveled, in pixels.

Plus, we can make the turtles change direction.

  • The command left means to turn left

  • The command “right” is to turn right

In this case, the arguments in parentheses indicate the Angle to be rotated.

Let’s look at an example of a turtle drawing a square. The code is as follows.

import turtle

turtle.forward(100)  # mobile
turtle.left(90)  Turn 90 degrees to the left
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
Copy the code

Running this code, you can see that the turtle has drawn a square facing down, as shown in Figure 3.

In case you’re wondering, we haven’t seen any turtles, even though they’re called turtles.

This is because, by default, the cursor is an arrow, and if you want to see the cute little turtle, you need to call shape() and pass turtle as an argument to the method.

Alternatively, setheading() can be called to set the direction in which the turtle starts, with a number as the parameter indicating the Angle to be rotated. Let’s look at an example that looks like this.

import turtle

turtle.shape("turtle")
turtle.forward(100)
turtle.setheading(180)
Copy the code

In this code, we first change the cursor to the turtle, then draw a straight line, and then ask the turtle to turn its head. The final result is shown in Figure 4.

There is also a home() method, which means to return the baby turtle to the original brush position. Let’s add the sentence turtle.home() to the end of the code, as follows.

import turtle

turtle.shape("turtle")
turtle.forward(100)
turtle.setheading(180)
turtle.home()
Copy the code

The end result is that the baby turtle is back where it started, as shown in Figure 5.

One thing to note here, though, is that turtle.home() goes back to the beginning and the process will be drawn as well. For example:

import turtle

turtle.shape("turtle")
turtle.forward(100)
turtle.setheading(90)
turtle.forward(100)
turtle.home()
Copy the code

Baby turtles can draw circles and arcs as well as straight lines. We use thecircle()Function to draw a circle with a given radius. This function takes 3 arguments, which are:

  • Radius: The radius, a positive number indicating that the center of the circle is to the left of the brush, a negative number indicating that the center of the circle is to the right of the brush;

  • Extent: radian. This parameter is optional. If no value is specified, a circle is drawn.

  • Steps: Make the tangent regular polygon of the circle with radius radius. The number of sides of the polygon is steps. This is also an optional parameter.

Let’s try drawing a circle and see what it looks like. The code is as follows.

import turtle

turtle.circle(100.300)
Copy the code

The resulting graph is shown in Figure 6.

There are two more commonly used methods related to movement:

  • Turtle.goto (x, y) positions the brush to the specified coordinates;

  • Turtle.speed (speed) allows you to change the speed at which the brush runs.

Next, let’s try drawing a kite. Draw a line through the goto() method to represent the kite line and move the cursor to the top left corner. Then specify a speed of 2 for the turtle. Next, using the for loop, draw the kite head. The following code

import turtle
turtle.speed(2)
turtle.goto(-200.200)
for x in range(30):
    turtle.forward(x)
    turtle.left(90)
Copy the code

The result is shown in Figure 7.

Brush control

We can control the start and finish of the brush to determine whether to leave a trail of motion on the screen.

  • When callingpenup()Method, represents the start of the pen, in this state will not draw the trajectory of the movement;
  • When callingpendown()Method, which represents the stroke of the pen, will draw the trajectory of the motion in this state.

The way to think about it is that the turtle takes a pen, and the pen is either up or down, and when the pen is up, the turtle doesn’t draw anything as it moves, and when the pen is down, the turtle uses the pen to trace its path.

We changed the code we had just used to draw the kite. Now we have 5 similar kite heads in the center of the canvas and in the top, bottom, left and right corners. We have increased the speed of drawing to 10. The code is as follows.

import turtle

turtle.speed(10)
for x in range(100):
	turtle.forward(x)
	turtle.left(90)
turtle.penup()
turtle.goto(-200.200)
turtle.pendown()
for x in range(100):
	turtle.forward(x)
	turtle.left(90)
turtle.penup()
turtle.goto(200.200)
turtle.pendown()
for x in range(100):
	turtle.forward(x)
	turtle.left(90)
turtle.penup()
turtle.goto(-200, -200)
turtle.pendown()
for x in range(100):
	turtle.forward(x)
	turtle.left(90)
turtle.penup()
turtle.goto(200, -200)
turtle.pendown()
for x in range(100):
	turtle.forward(x)
	turtle.left(90)
Copy the code

color

Turtle painting is not limited to drawing with a black brush. You can use other color brushes and even fill shapes with color. Let’s introduce a few functions related to color.

  • Pencolor: Sets the brush color;

  • Fillcolor: sets the fillcolor.

  • Begin_fill: called before filling the shape;

  • End_fill: called after the shape is filled.

Light comes in three main colors: red, green, and blue (red, blue, and yellow are the main colors for painting and paint, but computer monitors use light, not paint). By combining different amounts of these three colors, any other color can be formed.

In Pygame, we use tuples of three integers to represent colors. The first value in the tuple, which indicates how much red is in the color. An integer value of 0 indicates that there is no red in the color, while 255 indicates that there is a maximum amount of red in the color. The second value indicates green, and the third value indicates blue. These tuples of three integers used to represent a color are often referred to as RGB values.

Since we can use any combination of 0 to 255 for the three main colors, this means that Pygame can draw 16, 777, 216 different colors, or 256×256×256 colors. However, if you try to use a value greater than 255 or a negative value, you’ll get an error like ValueError: Invalid Color Argument.

For example, we create tuples (0, 0, 0) and store them in a variable named BLACK. There is no amount of red, green and blue, and the final color is completely black. Black actually means no color value at all. The tuple (255, 255, 255) indicates that red, green, and blue are all maximized, resulting in white. White is a complete combination of red, green and blue. The tuple (255, 0, 0) indicates that red has reached its maximum, and there is no green or blue, so the final color is red. Similarly, (0, 255, 0) is green, and (0, 0, 255) is blue.

Let’s go through a simple example to see how to use colors:

  • First, call the pencolor() method to set the brush to red, followed by the fillcolor() method to set the fillcolor to green;

  • Then call the begin_fill() method to indicate that you want to start filling;

  • Next, call the circle() method to draw a circle with a red brush and a green fill, with a radius of 90 pixels;

  • Finally, the end_fill() method is called to finish the filling.

The code is as follows.

import turtle

turtle.pencolor("red")
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(90)
turtle.end_fill()
Copy the code

Run it, and the resulting graph looks like figure 9.

In addition to being able to directly enter the “English name” of the color (red, green in the sample code above), we can also directly specify the RGB color value of the color.

Turtle graphics has a colormode function that specifies the RGB color value range of 0 to 255 integers or 0 to 1 decimals. When the parameter is 255, the value is an integer ranging from 0 to 255. When the parameter is 1.0, a small value from 0 to 1 is used. Let’s look at an example that looks like this.

import turtle

turtle.colormode(255)
turtle.pencolor(255.192.203)
turtle.circle(90)
turtle.colormode(1.0)
turtle.pencolor(0.65.0.16.0.16)
turtle.circle(45)
Copy the code

We call colormode() twice, first passing it as an argument of 255, and then calling pencolor() with an integer between 0 and 255 to represent the RGB color value, indicating that the color of the brush is pink. And then I drew a big circle.

And then we call it againcolormode()Function, then called oncepencolor()The function takes a decimal between 0 and 1 to represent the RGB color value, indicating that the brush color is brown. And then I drew a little circle. Run the code, and you get something like figure 10.

AI yue chuang · launched tutorials, including “Python language tutorials, C++ tutorials, algorithm/data structure tutorials”, all one-to-one teaching: one-to-one tutoring + one-to-one q&a + assignment + project practice, etc. QQ, wechat online, at any time to respond! V: Jiabcdefh

Public number: AI Yue Chuang, the later video tutorial, please pay attention to!