Introduction to Turtle Graphics in Python
by K. Yue
1. Turtle Graphics
- The Python turtle module is a built-in library that provides a way to create graphics and drawings.
- In turtle graphics, there are two major concepts:
- A window/screen/digit canvas for the turtle to move and draw.
- A turtle with a pen that can move and draw (if the pen is down).
Turtle:
- The turtle is:
- in a co-ordinate location (x,y), initially (0,0)
- facing a direction (initially right)
- holding a pen which can be up and down (initially down). If the pen is down, the turtle draws while moving.
- There are functions to control the turtle. Two popular ones are:
- forward(distance): move the turtle forward by a distance. If the pen is down, the turtle also draws.
- 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()
- Download and run square2.py.txt. This is a version of square.py.txt that you can use as the basis of your HW assignment.
- Also, try to run it in IDLE by copying and pasting one statement at a time.
Explanations:
- "import turtle": import the built-in turtle module. This allows the program to use the turtle object.
- "pen = turtle.Turtle()" creates a turtle object and refers to it as "pen"
- "pen.forward(100)" moves the pen. Since the pen is down, the turtle also draws.
- "pen.right(90)" turns the turtle right 90 degrees.
- screen.exitonclick(): pause until the screen is clicked on to exit.