Introduction
Turtle Graphics is a Python library that allows us to create pictures and shapes by controlling a turtle on the screen. The turtle moves around the screen, drawing lines as it moves. By controlling its direction and speed, you can draw intricate shapes and patterns. This method of programming is great for learning the basics of programming, as it allows you to visualize code behavior in real-time.
Objective
The objective of this program is to use Python’s Turtle Graphics library to draw different shapes and patterns. We will draw a simple square, circle, and a more complex pattern using loops and the turtle module.
Python Code Using Turtle Graphics
import turtle # Setting up the screen screen = turtle.Screen() screen.bgcolor("white") # Creating a turtle object t = turtle.Turtle() t.shape("turtle") t.speed(5) # Function to draw a square def draw_square(): for _ in range(4): t.forward(100) t.left(90) # Function to draw a circle def draw_circle(): t.circle(100) # Function to draw a pattern def draw_pattern(): for _ in range(36): draw_square() t.right(10) # Drawing a square t.penup() t.goto(-150, 0) t.pendown() draw_square() # Drawing a circle t.penup() t.goto(150, 0) t.pendown() draw_circle() # Drawing a pattern of squares t.penup() t.goto(0, 0) t.pendown() draw_pattern() # Hiding the turtle and finishing the drawing t.hideturtle() # Closing the window on click screen.exitonclick()
Program Explanation
The code starts by setting up the screen for drawing with a white background. We create a turtle object and set its shape to a turtle and its speed to 5 for smooth drawing.
- draw_square() function: This function draws a square by moving the turtle forward by 100 units and turning left by 90 degrees, repeating this 4 times to complete the square.
- draw_circle() function: This function uses the turtle’s
circle()
method to draw a circle with a radius of 100 units. - draw_pattern() function: This function draws 36 squares in a circular pattern by calling the
draw_square()
function and turning the turtle right by 10 degrees after each square.
After defining the functions, we position the turtle to different coordinates to draw the square, circle, and pattern at distinct locations on the screen. Finally, the turtle is hidden, and the program waits for the user to click on the window to close it.
How to Run the Program
To run this program on your local machine:
- Make sure you have Python installed. If not, download and install Python from here.
- Install the
turtle
module (it comes pre-installed with Python, so you don’t need to install anything extra). - Save the code in a file with a
.py
extension, for example,turtle_graphics.py
. - Open your command line (or terminal) and navigate to the folder where the file is saved.
- Type
python turtle_graphics.py
and hit Enter to run the program.