Ora

How to Insert a Shape in Python?

Published in Python Graphics and Drawing 7 mins read

You can insert or draw shapes in Python using various libraries, with the turtle graphics module being an excellent and accessible choice for beginners. For more advanced applications, libraries like Pillow, OpenCV, or Matplotlib offer powerful capabilities for image manipulation and data visualization.


Drawing Shapes with Python Turtle Graphics

The turtle module provides a simple way to create graphics and shapes. It's often used for teaching programming due to its visual feedback and straightforward commands. The concept involves a "turtle" cursor that you move around on a canvas, leaving a trail behind it to form shapes.

Getting Started with Turtle

To begin drawing shapes, you first need to import the turtle module. By default, the turtle's starting position (its X and Y coordinates) is (0,0), the center of the drawing window. This is analogous to initializing its primary position variables to zero.

Example: Basic Turtle Setup

import turtle

# Get a screen object to control the window
screen = turtle.Screen()
screen.setup(width=600, height=400) # Optional: Set window size
screen.bgcolor("lightblue") # Optional: Set background color

# Create a turtle object
pen = turtle.Turtle()

# You can adjust the drawing speed. Sending 0 to the speed() function
# makes the turtle draw as fast as possible, without animation delay.
pen.speed(0)

# The turtle is now ready to draw!
# For example, to move forward 100 pixels:
pen.forward(100)

# Keep the window open until it's manually closed
screen.mainloop()

Adjusting Drawing Speed

Controlling the turtle's drawing speed is crucial for animations or quick shape generation. The turtle.speed() function allows you to set this:

Speed Value Description
0 Fastest (no animation, instant drawing)
1 Slowest
10 Fast
any number 1-10 Intermediate speed (e.g., 6 for normal)

Using pen.speed(0) as shown above will render shapes instantly without visual animation, which is great for quickly displaying the final output.

Drawing Common Shapes

Here's how to draw various shapes using the turtle module:

  • Square:
    A square has four equal sides and four 90-degree angles.

    import turtle
    screen = turtle.Screen()
    pen = turtle.Turtle()
    pen.speed(0) # Draw instantly
    
    pen.color("blue", "cyan") # Set pen color and fill color
    pen.begin_fill()          # Start filling the shape
    for _ in range(4):
        pen.forward(100)      # Move forward 100 units
        pen.right(90)         # Turn right 90 degrees
    pen.end_fill()            # End filling
    
    screen.mainloop()
  • Circle:
    The circle() method draws a circle with a specified radius.

    import turtle
    screen = turtle.Screen()
    pen = turtle.Turtle()
    pen.speed(0)
    
    pen.penup() # Lift the pen to move without drawing
    pen.goto(-50, -50) # Move to a starting position for the circle
    pen.pendown() # Put the pen down
    
    pen.color("red", "orange")
    pen.begin_fill()
    pen.circle(70) # Draw a circle with radius 70
    pen.end_fill()
    
    screen.mainloop()
  • Triangle:
    A simple equilateral triangle can be drawn by moving forward and turning 120 degrees three times.

    import turtle
    screen = turtle.Screen()
    pen = turtle.Turtle()
    pen.speed(0)
    
    pen.penup()
    pen.goto(-70, 0)
    pen.pendown()
    
    pen.color("green", "lightgreen")
    pen.begin_fill()
    for _ in range(3):
        pen.forward(140)
        pen.left(120) # Turn 120 degrees for an equilateral triangle
    pen.end_fill()
    
    screen.mainloop()
  • Custom Polygons:
    You can draw any regular polygon by adjusting the number of sides and the turn angle (360 degrees / number of sides).

    import turtle
    screen = turtle.Screen()
    pen = turtle.Turtle()
    pen.speed(0)
    
    num_sides = 5 # Pentagon
    side_length = 80
    angle = 360 / num_sides
    
    pen.penup()
    pen.goto(-40, 50)
    pen.pendown()
    
    pen.color("purple", "violet")
    pen.begin_fill()
    for _ in range(num_sides):
        pen.forward(side_length)
        pen.right(angle)
    pen.end_fill()
    
    screen.mainloop()

Key Turtle Functions for Drawing:

  • forward(distance): Moves the turtle forward.
  • backward(distance): Moves the turtle backward.
  • right(angle): Turns the turtle right by the specified angle.
  • left(angle): Turns the turtle left by the specified angle.
  • penup(): Lifts the pen, so moving the turtle doesn't draw.
  • pendown(): Puts the pen down, so moving the turtle draws.
  • goto(x, y): Moves the turtle to an absolute position (x, y).
  • color(pencolor, fillcolor): Sets the pen color and the fill color for shapes.
  • begin_fill(): Marks the starting point for a shape to be filled.
  • end_fill(): Fills the shape drawn since begin_fill() was called.
  • pensize(width): Sets the thickness of the drawing pen.
  • hideturtle(): Makes the turtle cursor invisible.
  • showturtle(): Makes the turtle cursor visible.

Other Python Libraries for Inserting Shapes

While turtle is excellent for learning and simple graphics, other libraries offer more robust features for different use cases.

Pillow (PIL Fork)

Pillow is a powerful imaging library that adds image processing capabilities to your Python interpreter. It can be used to create new images or draw shapes on existing ones.

  • Use Cases: Creating thumbnails, image manipulation, adding text, drawing basic shapes on bitmaps.
  • How it Works: You create an Image object and then an ImageDraw object from it, which provides drawing methods.
from PIL import Image, ImageDraw

# Create a blank image (white background)
img = Image.new('RGB', (200, 150), color = 'white')
d = ImageDraw.Draw(img)

# Draw a rectangle
# (x0, y0, x1, y1) specifies the bounding box
d.rectangle([(20, 20), (100, 80)], fill="blue", outline="black")

# Draw a circle (ellipse within a square bounding box)
# (x0, y0, x1, y1) specifies the bounding box
d.ellipse([(120, 30), (180, 90)], fill="red", outline="green")

# Draw a line
d.line([(30, 120), (170, 100)], fill="purple", width=3)

img.save('shapes_pillow.png')
# img.show() # Uncomment to display the image

OpenCV (Open Source Computer Vision Library)

OpenCV is primarily used for computer vision tasks but includes powerful functions for drawing shapes on images and video frames.

  • Use Cases: Real-time object detection, image analysis, video processing, drawing annotations.
  • How it Works: Images are treated as NumPy arrays. OpenCV functions directly manipulate these arrays to draw shapes.
import cv2
import numpy as np

# Create a black image (NumPy array)
image = np.zeros((300, 500, 3), dtype=np.uint8)

# Draw a rectangle: cv2.rectangle(img, pt1, pt2, color, thickness)
cv2.rectangle(image, (50, 50), (200, 200), (0, 255, 0), -1) # Green, filled

# Draw a circle: cv2.circle(img, center, radius, color, thickness)
cv2.circle(image, (350, 125), 70, (0, 0, 255), 5) # Red, thickness 5

# Draw a line: cv2.line(img, pt1, pt2, color, thickness)
cv2.line(image, (20, 250), (480, 280), (255, 255, 0), 2) # Yellow, thickness 2

# Display the image (optional)
# cv2.imshow("Shapes with OpenCV", image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# Save the image
cv2.imwrite('shapes_opencv.png', image)

Matplotlib

Matplotlib is a plotting library that provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits. It can also be used to draw geometric shapes.

  • Use Cases: Data visualization, scientific plotting, creating complex charts and graphs.
  • How it Works: Shapes are added as "patches" to an Axes object.
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots(1)

# Draw a rectangle
rect = patches.Rectangle((0.1, 0.6), 0.3, 0.2, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)

# Draw a circle
circle = patches.Circle((0.7, 0.3), 0.15, linewidth=2, edgecolor='b', facecolor='g', alpha=0.5)
ax.add_patch(circle)

# Set limits and aspect ratio
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect('equal', adjustable='box')

plt.title("Shapes with Matplotlib")
plt.show()
# fig.savefig('shapes_matplotlib.png') # Uncomment to save the figure

Choosing the Right Library

Library Best For Learning Curve Features
turtle Educational purposes, simple animations, quick graphical output. Low Easy drawing of lines, circles, polygons, basic colors.
Pillow Image creation, manipulation, adding shapes/text to existing images. Medium Image filtering, resizing, cropping, drawing basic shapes.
OpenCV Computer vision applications, real-time drawing on video frames, complex image processing. High Advanced image/video processing, object detection, sophisticated drawing tools.
Matplotlib Data visualization, plotting data, embedding shapes into scientific plots. Medium Extensive plotting capabilities, various shape patches, customization.

Each library offers unique advantages depending on your specific needs for inserting or drawing shapes in Python.