© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
A. ElumalaiIntroduction to Python for Kids https://doi.org/10.1007/978-1-4842-6812-4_7

7. A Turtle Deep Dive

Aarthi Elumalai1  
(1)
Chennai, Tamil Nadu, India
 

In the previous chapter, you were introduced to the Turtle library in Python. We looked at drawing lines and shapes with Turtle, and we even learned how to draw a mandala design entirely composed of lines.

In this chapter, we’re going to take a deeper look into Turtle. You’ll learn how to draw colors to your designs and draw circles and arcs of all shapes, sizes, and angles. You’ll also learn how to draw text on screen. At the end of the chapter, you’ll learn how to change the angles of your drawings and finally draw smileys or drawings of any kind.

Customize your screen

What use are graphics and images without colors? Right now, your screen looks boring. It has a white background, and your screen title is always “Python Turtle Graphics”. You can change all of that though.

../images/505805_1_En_7_Chapter/505805_1_En_7_Figa_HTML.jpg
To start with, you can change your screen title using the title method but remember something. This function isn’t a part of t (turtle.Turtle). You need to preface it with turtle, the actual package, like this:
turtle.title('Hello Turtle!')

The same goes for your background color. You need to use the bgcolor method to change your background color and specify your color, in words, within either single (‘) or double (“) quotes.

I’m going to change my screen’s background color to red.
turtle.bgcolor('red')
Would you like to look at the changes we made? Look at the yellow arrow (I drew that in Figure 7-1). Our title now says “Hello Turtle!” and our screen is red. Perfect!
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig1_HTML.jpg
Figure 7-1

Background color set to red

Try changing your screen to a different color or title.

You’re not limited to the basic colors either. Follow this link: https://en.wikipedia.org/wiki/Web_colors.

You’ll find the names of hundreds of colors on there. Let your imagination run free!

Customize your graphics

You know how to change the background color of the screen. Great! But what about the image color? Colored pens and images filled in color are a staple of any good drawing, aren’t they?

So, you can change the color of your pen (outline of your graphics) and your graphic (fill color). You can also set a size for your lines and change the speed of your turtle (pen) if you feel it’s too slow.

To change the color of your pen, use the pencolor function (write the function as it is, in all small letters) and give the name of the color as the parameter (what you give within the brackets). I’m going to use one of the colors from the color chart I gave you a link to in the last section.

Similarly, to change your fill color, use the fillcolor function. You can increase the size of your pen (the thickness of your lines) with the pensize function and give a number as its parameter. Specify a number greater than 2 to really see a difference, since 1 is the default pen size. Also, you can increase the speed of your pen by using the speed function. The default speed value is 1, so give anything more than that and you’ll see a change.

Let’s apply all of this and look at the result.
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
turtle.title('Hello Turtle!')
turtle.bgcolor('DarkOrchid')
t.pencolor('Salmon')
t.fillcolor('Chartreuse')
t.pensize(5)
t.speed(7)
t.goto(0,100)
t.goto(100,100)
t.goto(100,0)
t.home()
Alright. I’ve specified the background color as “Dark Orchid”, the pen color as “Salmon”, the fill color as “Chartreuse”, the pen size as 5, and the speed as 7. I’ve also drawn a square with goto. Let’s see if it works (Figure 7-2).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig2_HTML.jpg
Figure 7-2

Set speed, size, pen color, and background color

It has worked to an extent. My pen drew so fast that I didn’t see it draw this time (bummer). The lines are thick, the pen color is indeed salmon, but where is the fill color?

That’s because Turtle wants you to indicate when you want the filling to start and end, so it doesn’t accidentally fill something it shouldn’t (like just two lines joined at a point).

You need to use the begin_fill() method when you want the fill to start and the end_fill() method when you want it to end.

So, after I’ve typed out the lines of code required to change the colors, size, and speed, this is what I’d do when I draw the shape:
t.begin_fill()
t.goto(0,100)
t.goto(100,100)
t.goto(100,0)
t.home()
t.end_fill()
Now, when I run my program, I’ll get this (Figure 7-3).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig3_HTML.jpg
Figure 7-3

Set fill color of the rectangle

Yes, it works!

Also, you can use shortcuts for your formatting. Instead of using two lines of code to specify pen and fill color, you can use one, like this:
t.color('Salmon','Chartreuse')

The first value is for pencolor and the second is for fillcolor.

Or, better yet, you can use a single line for all the four formatting options, like this:
t.pen(pencolor='Salmon', fillcolor="Chartreuse", pensize=5, speed=7)

Notice how you didn’t have to place the numbers within quote. When you use the preceding line of code in your script, you’ll notice that the result has not changed at all.

You can omit any of those arguments (pencolor='Salmon' is an argument) as per your requirement.

Before we end this section, I want you to try something. I want you to specify the value of speed as 0. What do you think will happen? Will turtle start drawing our square at the speed of an actual turtle? Or would you be pleasantly surprised? Try and see! ../images/505805_1_En_7_Chapter/505805_1_En_7_Figd_HTML.gif

Shapes without lines

We’ve been looking at drawing lines so far, but what if you want to draw circles? There’s a pre-defined function for that as well. It’s called “circle”, and you have to give just the radius as the argument within the brackets. Radius is basically the size of the circle.

Let’s try one, shall we?

Circles

s = turtle.getscreen()
t = turtle.Turtle()
t.circle(100)
I’ve kept it simple. Run the preceding code, and you’ll get this (Figure 7-4).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig4_HTML.jpg
Figure 7-4

Draw a circle – anti-clockwise direction

As you can see, turtle started drawing the circle from the default 0,0 position in the anti-clockwise direction (toward the left) so the circle was drawn above the 0,0 position.

If I gave a negative value for radius, it’ll draw in the clockwise direction, that is, below the 0,0 position. Let’s try.
t.circle(-100)
Run the above lines of code, and you’ll get this (Figure 7-5).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig5_HTML.jpg
Figure 7-5

Draw a circle – clockwise direction

You can use the same coloring and size options you used on your straight lines for your circle.

As a small activity, I want you to draw different colored circles with different colors and see what you get.

Dots

You can draw a dot with the “dot” function. It’s just a filled in circle that uses the pen color to fill itself, or you can give a preferred color in the second parameter.
t.dot(100, 'Salmon')
Run the preceding code, and you’ll get this (Figure 7-6).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig6_HTML.jpg
Figure 7-6

Draw colored dot

Did you notice something? The size of our circle is considerably bigger than our dot. That is because the value we give inside our dot function is actually the diameter, not the radius. So, your circle, with the same value, is going to be twice as big as your dot.

Arcs

Now, let’s draw an arc! Arcs are part of a circle, aren’t they? So, we are still going to use the circle function, but we’re going to add more parameters to let turtle know that it should only draw a part of the circle (arc).

You know how angles work, don’t you? (Figure 7-7)
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig7_HTML.jpg
Figure 7-7

Angles in a circle

360 degrees makes a circle, so if you want a semi-circle, you need just 180 degrees. To make a quarter circle (arc), you need 90 degrees. We’re going to make a semi-circle now.
t.circle(100,180)
Run the preceding code, and you’ll get this (Figure 7-8).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig8_HTML.jpg
Figure 7-8

Draw a semi-color

When you give the values as –100,180, you’ll get the same arc, but below. Give 100,–180 and you’ll see a mirror image of the first arc, and for –100,–180, you’ll see the same mirror image, but below the 0,0 position. Try out and see for yourself!

If you gave the angle as 90 degrees, you’d draw quarter of a circle. Why don’t you play around with the angles to get different sized arcs? Don’t just stop at 90 or 180. You have angles from 0 to 360 to play around with. Have fun! ../images/505805_1_En_7_Chapter/505805_1_En_7_Fige_HTML.gif

More options!

We have a lot more options with Turtle, but since we are just covering the basics in this chapter, I’ll just talk about a couple more before we move on to the projects. Sometimes, you might want to draw more than one shape or figure on your screen, and they might be in different places. So, you need a way to move your pen to the new location without drawing anything on the move. Once moved, your pen should start drawing again. The penup and pendown methods (all small letters) help you do exactly that.

When you give the “penup” command to your turtle, you’re asking it to take the pen off the screen. It won’t draw anymore, but it will move positions based on your forward, backward, or goto commands. The command “pendown” does the exact opposite. If you want your pen to draw again, give it the pendown command. This command will only work if the penup command is in effect.

Also, you can use the hideturtle function after your program finishes drawing your graphics to hide the turtle from the screen. I’m sure you’d be relieved to learn of this method. I know I was. Those turtles didn’t look good on my images!

I know I just dumped a bunch of random methods on you, and you might be confused. So, why don’t we put what we just learned to test? Let’s draw a square and then a circle, on different sides of the screen, and hide the turtle at the end, shall we?
  1. 1.
    I’m going to use “penup” when I start the program (after I set up turtle as usual) and then send the pen to the position (–200,200). Once my pen has moved, I’m going to specify pendown because I’m going to draw my square next.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
    t.penup()
    t.goto(-200,200)
    t.pendown()
     
  2. 2.

    Then, I’m going to set the fillcolor to blue for my square.

     
t.fillcolor('blue')
  1. 3.
    I’m going to use the usual lines of code to draw my square next.
    #Draw the square
    t.begin_fill()
    t.goto(-100,200)
    t.goto(-100,100)
    t.goto(-200,100)
    t.goto(-200,200)
    t.end_fill()
     
  2. 4.
    Once drawn, I need to change positions again to draw my circle. So, penup again, go to (200,–200), which is on the opposite side of the screen, and then pendown.
    #Change positions again
    t.penup()
    t.goto(200,-200)
    t.pendown()
     
  3. 5.

    I’m going to set the fill color as red for my circle.

     
t.fillcolor('red')
  1. 6.
    Then, I’m going to draw a 50-point radius circle.
    #Draw the circle
    t.begin_fill()
    t.circle(50)
    t.end_fill()

    That’s it! We have two shapes on opposite sides of the screen! ../images/505805_1_En_7_Chapter/505805_1_En_7_Figf_HTML.gif

     
  2. 7.

    Finally, I’m going to use the hideturtle() function to hide the turtle (which would still be shown on the circle otherwise).

     
t.hideturtle()
When you run the program, you’d get this (Figure 7-9).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig9_HTML.jpg
Figure 7-9

Hide the “t” turtle

  1. 8.

    Now this is where you’ll find things a bit different. If I just use t.hideturtle(), then I’ll only hide one of the turtles (why don’t you draw and see?). But you must have noticed that there are two turtles. There’s one at the home position (0,0), which pertains to the turtle package itself, and there’s another (t of the pre-defined function Turtle()) that does the drawing.

     
So, we need hideturtle() repeated twice. We already wrote hideturtle() for “t”. Let’s write another one for the “turtle” package in its entirety.
turtle.hideturtle()
Once I’ve added the preceding line of code, let’s run the script again (Figure 7-10).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig10_HTML.jpg
Figure 7-10

Hide the “turtle” turtle

Look at that! The turtle in the center of the screen has disappeared as well. Yes!

Draw text on screen

We’ve drawn all kinds of graphics so far, but no image is complete without a little bit of text, is it? And it’s quite simple too. Would you like to see?

../images/505805_1_En_7_Chapter/505805_1_En_7_Figb_HTML.jpg
To write a simple text, just use the write method of Turtle, and specify the text you want displayed, like this:
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
t.write('Hello there!')
Run it, and you’ll get this (Figure 7-11).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig11_HTML.jpg
Figure 7-11

Draw text on screen

That looks like chicken scrawl. Aww! Could we manipulate this text in any way? You bet!

Let’s position our text somewhere first.
t.penup()
t.goto(200,200)
t.pendown()
Now, let’s draw again, but with a slight change:
t.write('Hello there!', move=True)
The move argument is False by default. If you make it true, you’ll see the arrow below the text being drawn, like this (Figure 7-12).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig12_HTML.jpg
Figure 7-12

Draw text in a different position

You might not see much difference now since the text is too small and too short.

Still too small! Let’s add some styles, shall we? You know the different font styles you can use on your text, don’t you? There’s Arial, Calibri, Times New Roman, and a ton of styles like that. A simple Google search will give you a list of them.

I’m going to make mine Georgia. But that’s not where it ends. I can also increase or decrease the font size and change the font type. Let’s play with them all!

Let’s change position again to make room for the “big” text we’ll be creating:
t.penup()
t.goto(-200,200)
t.pendown()

The x position is now –200, instead of 200.

Now, let’s draw our text.
t.write('Hello there!', move=True, font=('Georgia',40,'normal'))
Did you notice something in the above code? I’ve mentioned all the styles under “font”, and they’re within a combined parenthesis. Also, the font style (‘Georgia’) and type (‘normal’) are within quotes (can be single or double quotes). Let’s run the above code, and we’ll get this (Figure 7-13).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig13_HTML.jpg
Figure 7-13

Format the text

You can change the color of your text by using the pencolor tool.
t.pencolor('Red')
You can also make your text bold, italics, and underlined (or any of those three) by including them as values alongside the rest of the font values, like this:
t.write('Hello there!', move=True, font=('Georgia',40,'normal','bold','italic','underline'))
Run the preceding code, and you’ll get this (Figure 7-14).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig14_HTML.jpg
Figure 7-14

Change the color of the text

Looking good! ../images/505805_1_En_7_Chapter/505805_1_En_7_Figh_HTML.gif

Mini project – circle within a square

This is going to be a simple project. We’re going to draw a circle inside a square in this project:
  1. 1.
    Let’s set up turtle first. I’ve not set up the speed in this program, but you can do so.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.
    Next, I’ve set the fill color of the square to ‘Red’ and pen size to 5. I’m going to draw the square first and then the circle within it.
    #Set the color and pen size for the square
    t.fillcolor('Red')
    t.pensize(5)
     
  3. 3.
    Let’s draw the square now. I’m going to go to the position –100,–100 first so I can draw the circle around the center of the screen (0,0). This way, I can draw the circle around the same center point.
    #Draw the square
    t.penup()
    t.goto(-100,-100)
    t.pendown()
    t.begin_fill()
    t.goto(-100,100)
    t.goto(100,100)
    t.goto(100,-100)
    t.goto(-100,-100)
    t.end_fill()
     
  4. 4.
    Now, to set the circle’s center as 0,0, I’ve asked my pen to go to the position 0,–100, so when I draw a 100-point radius from this point, in the anti-clockwise direction (default), the center would be 0,0. I’ve set the fillcolor for the circle as ‘Blue’.
    #Set position so the circle's center is 0,0
    t.penup()
    t.goto(0,-100)
    t.pendown()
    #Draw the circle
    #Color and size
    t.fillcolor('Blue')
    #Circle
    t.begin_fill()
    t.circle(100)
    t.end_fill()
     
  5. 5.
    Finally, let’s hide the turtles.
    t.hideturtle()
    turtle.hideturtle()
     
Now, let’s run the entire code, and see if we get what we want (Figure 7-15).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig15_HTML.jpg
Figure 7-15

Circle within a square

Whohoo! :D

Change directions of your drawing

So far, the only way to change directions is by using the right() and left() methods. But, while creating arcs, you might want something else that changes the angle of your pen so you can place the arc wherever you want. What if you want to draw an eyebrow? Or a sideways smile?

Turtle offers you the setheading() method to do just that. Let’s look at what a heading is first. The heading() method gives you the angle of the pen at that particular time.
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
print(t.heading())
When I run the preceding code, I get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32drawTurtle.py
0.0

Right now, the pen is at an angle of 0, which means it’ll draw in the horizontal direction. But with setheading(), I can change the angle.

Let’s make it 90 degrees, perhaps. Just mention the angle within the brackets, and you’re good to go.
t.setheading(90)
Now let’s check the heading.
print(t.heading())
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32drawTurtle.py
90.0
Okay great, the heading is 90 degrees. What does that mean for us? Shall we draw a line and check?
t.pensize(5)
t.forward(100)
When we run the preceding lines of code, we’ll get this (Figure 7-16).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig16_HTML.jpg
Figure 7-16

Set heading to 90 degrees

Look at that! It drew a line upward, so when the heading is 90 degrees, the pen is pointing upward. You already know where each angle is, so you can guess where your pen will point for each angle change you make with setheading(), but let’s demonstrate the same with a small program, shall we? We’re starting fresh, so please open a new script or clear the one you’re currently using.
  1. 1.
    Let me start off with setting up the turtle. I’m going to print the current heading (0 degrees when the program starts running, which points toward the right). I’ve also increased the pen size to 5 and speed to 5.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
    print(t.heading())
    t.pensize(5)
    t.speed(5)
     
  2. 2.
    Now, I’m going to make the pen draw forward 100 points at the current degree. Once drawn, I’ll make the pen write the current degree using the heading() method. Then let’s lift the pen and go back to (0,0) to start anew.
    #0 degrees
    t.forward(100)
    t.write(t.heading())
    t.penup()
    t.home()
    t.pendown()
     
  3. 3.
    Now, let’s change the heading to 90 degrees (point upward) and draw forward and repeat the same as earlier.
    #90 degrees
    t.setheading(90)
    t.forward(100)
    t.write(t.heading())
    t.penup()
    t.home()
    t.pendown()
     
  4. 4.
    Now, 180 degrees (point toward the left).
    #180 degrees
    t.setheading(180)
    t.forward(100)
    t.write(t.heading())
    t.penup()
    t.home()
    t.pendown()
     
  5. 5.
    Finally, 270 degrees (pointed downward).
    #270 degrees
    t.setheading(270)
    t.forward(100)
    t.write(t.heading())
    Finally, let’s hide all the turtles.
    t.hideturtle()
    turtle.hideturtle()
     
Run the preceding code, and you’ll get this (Figure 7-17).
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig17_HTML.jpg
Figure 7-17

An angle diagram for setheading

Do you see the significance of using the setheading()? You can set your angle to any point you want. Right now, we’ve just set it to draw vertical or horizontal lines. Why don’t you change to angles and see what you get?

Mini project – smiley

In this project, let’s take things to the next level, shall we? Let’s draw a smiley face!
  1. 1.
    I’ve set up the Turtle package. You can change the speed if you like.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.
    Next, I’ve asked the pen to go to the position 0,–100 so I can draw a circle, which is our face, with the center of the circle as 0,0. This’ll just let me do the calculations for the eyes, nose, and mouth better.
    #Let's draw a smiley
    #Go to the position
    t.penup()
    t.goto(0,-100)
    t.pendown()
     
  3. 3.
    Now, let’s draw the face. The fillcolor is going to be yellow, and the pen size is going to be 5 and the circle is going to be of a radius of 100 points.
    #Draw the face
    #Color and size
    t.fillcolor('yellow')
    t.pensize(5)
    #Circle
    t.begin_fill()
    t.circle(100)
    t.end_fill()
     
  4. 4.

    Next, I’m going to draw the eyes. I set the positions based on trial and errors. You can use the same in your program or change the positions to see what you get and create your own (I recommend doing this).

     
I’m going to ask my pen to go to the position –40,30 to draw the left eye and draw a black dot with diameter 30.
#Draw the eyes
#First eye
t.penup()
t.goto(-40,30)
t.pendown()
t.dot(30)
  1. 5.
    Then, go to the position 40,30 (same horizontal line, opposite X value) and draw the right eye, which is again a dot with diameter 30.
    #Second eye
    t.penup()
    t.goto(40,30)
    t.pendown()
    t.dot(30)
     
  2. 6.
    Next, let’s draw the nose. This is where centering the circle at 0,0 comes in handy because our smiley’s nose is going to start from 0,0. Let’s draw a straight line from 0,0 down to 0,–30.
    #Draw the nose
    t.penup()
    t.goto(0,0)
    t.pendown()
    t.goto(0,-30)
     
  3. 7.
    Finally, the tricky part. Let’s draw the smile. We’re going to make the turtle go to the x position of the first eye, which is –40, but the y position is also going to be –40. Again, I found this value after a lot of trial and error, and I ended up with a value that gave me the result I want. Try your own! ../images/505805_1_En_7_Chapter/505805_1_En_7_Figg_HTML.gif
    #Draw the smile
    #Go to the x position of the first eye but a different y position
    t.penup()
    t.goto(-40,-40)
    t.pendown()
     
  4. 8.

    A smile is a semi-circle, isn’t it? But, if you try to draw a semi-circle as it is right now (try), you’ll get a slanted smile, not the only we see on smileys. This is where setheading comes in. We need to change the angle of the pen so we can draw the semi-circle in the exact angle we want. Let’s change the angle to –60. Don’t be confused! It’s the same as setting the angle to 120 (you can use either).

    Next, let’s draw a semi-circle with the angle 120, so it’s not exactly a semi-circle, but not a quarter circle either – something in between.
    #Change the direction of the pen (turtle)
    t.setheading(-60)
    t.circle(40,120)
     
  5. 9.
    Finally, let’s hide our turtles!
    #Finally, hide the turtle
    t.hideturtle()
    turtle.hideturtle()
     
Whew! That was long. Now shall we run the code and check to see if our efforts bore fruit? (Figure 7-18)
../images/505805_1_En_7_Chapter/505805_1_En_7_Fig18_HTML.jpg
Figure 7-18

Smiley face

Yay! That’s a cute little smiley! Why don’t you try creating different smileys? Maybe a sad smiley? Frowny face, or laugh? You have the tools you need (goto, setheading, etc.) to creating any image now, not just faces!

../images/505805_1_En_7_Chapter/505805_1_En_7_Figc_HTML.jpg

Summary

In this chapter, we went deeper into the Python Turtle module. We learned how to use colors, draw arcs, circles and dots, and manipulate their direction and size, and finally, how to draw text into our screen.

In the next chapter, let’s go deep into strings, how to create them and use them, and the various pre-defined string methods Python equips you with, and finally, let’s make some magic with them!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.135.202