Introduction to Turtle Graphics in Python

by K. Yue

1. Turtle Graphics

Turtle:

  1. The turtle is:
    1. in a co-ordinate location (x,y), initially (0,0)
    2. facing a direction (initially right)
    3. holding a pen which can be up and down (initially down). If the pen is down, the turtle draws while moving.
  2. There are functions to control the turtle. Two popular ones are:
    1. forward(distance): move the turtle forward by a distance. If the pen is down, the turtle also draws.
    2. right(degree): turn its face to right with a degree.

Example:

Consider square.py.txt (remove .txt when download):

import turtle

# Create a screen object in turtle
screen = turtle.Screen()

# Set screen dimensions
screen.setup(width=300, height=300)

# Set background color
screen.bgcolor("lightyellow")

# Create a turtle object
pen = turtle.Turtle()
pen.shape("turtle") # Change the turtle's shape
pen.color("green") # Set the turtle's color
pen.pensize(3) # Set the pen's size

pen.forward(100) # Move forward by 100 units
pen.right(90)
pen.forward(100) # Move forward by 100 units
pen.right(90)
pen.forward(100) # Move forward by 100 units
pen.right(90)
pen.forward(100) # Move forward by 100 units

screen.exitonclick()
 

Explanations: