9.1 Turtle module
The Python turtle
module provides a fun way to introduce programming to beginners through simple drawing and graphics. It allows you to control a turtle
, which can move around the screen, drawing lines as it goes. This topic will guide you through the basics of using the turtle
module.
9.1a Getting started
1.Import the turtle module:
2.Create a turtle object:
# Create a screen object
screen = turtle.Screen()
# Create a turtle object
my_turtle = turtle.Turtle()
3.Move the turtle:
- Move forward:
-
Turn left:
-
Turn right:
9.1b Drawing shapes
1.Drawing a square:
import turtle
screen = turtle.Screen()
my_turtle = turtle.Turtle()
for _ in range(4):
my_turtle.forward(100)
my_turtle.right(90)
turtle.done() # Finish the drawing
2.Drawing a triangle:
3.Drawing a circle:
import turtle
screen = turtle.Screen()
my_turtle = turtle.Turtle()
my_turtle.circle(50) # Draw a circle with radius 50
turtle.done()
9.1c Changing turtle attributes
1.Changing the pen colour:
2.Changing the pen size:
3.Changing the turtle speed:
my_turtle.speed(1) # Slowest
my_turtle.forward(100)
my_turtle.speed(10) # Fastest
my_turtle.forward(100)
9.1d Advanced drawing
1.Drawing a star:
import turtle
screen = turtle.Screen()
my_turtle = turtle.Turtle()
for _ in range(5):
my_turtle.forward(100)
my_turtle.right(144)
turtle.done()
2.Using loops for patterns:
import turtle
screen = turtle.Screen()
my_turtle = turtle.Turtle()
for _ in range(36):
my_turtle.forward(100)
my_turtle.right(170)
turtle.done()
9.1e Handling User Events
1.Closing the window on click:
import turtle
screen = turtle.Screen()
my_turtle = turtle.Turtle()
my_turtle.circle(50)
# Close the window when clicked
screen.exitonclick()
9.1f Putting it all together
Example 9.1.1 - Here's a complete example that combines several concepts.
import turtle
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("lightyellow")
# Create a turtle
my_turtle = turtle.Turtle()
my_turtle.shape("turtle")
my_turtle.color("green")
my_turtle.speed(5)
# Draw a square
for _ in range(4):
my_turtle.forward(100)
my_turtle.right(90)
# Move the turtle to a new position without drawing
my_turtle.penup()
my_turtle.goto(-150, 0)
my_turtle.pendown()
# Draw a circle
my_turtle.pencolor("blue")
my_turtle.circle(50)
# Move the turtle to a new position without drawing
my_turtle.penup()
my_turtle.goto(150, 0)
my_turtle.pendown()
# Draw a star
my_turtle.pencolor("red")
for _ in range(5):
my_turtle.forward(100)
my_turtle.right(144)
# Finish drawing
turtle.done()
Note
This topic covers the basics of the turtle module, including creating a turtle, moving it around, drawing shapes, and customizing its attributes. The turtle module is a great way to start learning Python and practicing programming concepts in a visual and interactive way. Experiment with different shapes, colors, and patterns to get a feel for what you can create! You can also check this more in-depth tutorial on how to use the turtle module.