Python Turtle Module
Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig and Seymour Papert in 1966.
Importing the Module
import turtle
Basic Usage
To use turtle, you need to create a screen and a turtle object (though you can use the module functions directly for a default turtle).
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
t.forward(100)
t.right(90)
t.forward(100)
turtle.done() # Keeps the window open
Movement
forward(distance)orfd(distance): Move the turtle forward.backward(distance)orbk(distance): Move the turtle backward.right(angle)orrt(angle): Turn the turtle right.left(angle)orlt(angle): Turn the turtle left.goto(x, y): Move the turtle to position x,y.
t.fd(50)
t.lt(45)
t.bk(50)
Drawing Shapes
Circle
t.circle(50) # Radius 50
Square
for _ in range(4):
t.fd(100)
t.rt(90)
Pen Control
penup()orpu(): Lifts the pen up (no drawing).pendown()orpd(): Puts the pen down (drawing).pensize(width): Sets the thickness of the line.pencolor(color): Sets the color of the pen.
t.pu()
t.goto(-50, -50)
t.pd()
t.pensize(5)
t.pencolor("red")
t.circle(20)
Filling Shapes
To fill a shape with color:
- Set the fill color using
fillcolor(). - Call
begin_fill(). - Draw the shape.
- Call
end_fill().
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()
Screen Control
bgcolor(color): Sets the background color.title(string): Sets the window title.clearscreen(): Clears the screen.
turtle.bgcolor("blue")
turtle.title("My Turtle Program")