2 min read

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) or fd(distance): Move the turtle forward.
  • backward(distance) or bk(distance): Move the turtle backward.
  • right(angle) or rt(angle): Turn the turtle right.
  • left(angle) or lt(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() or pu(): Lifts the pen up (no drawing).
  • pendown() or pd(): 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:

  1. Set the fill color using fillcolor().
  2. Call begin_fill().
  3. Draw the shape.
  4. 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")

programming/python/python