Python Turtle Graphics: Build a Spirograph Drawing App

andreasBlog2 weeks ago41 Views

Skill level: Beginner-friendly
What you’ll learn: Loops, functions, random colors, and Python’s built-in turtle graphics module.
Outcome: A colorful spirograph pattern generator — readers can run it locally or in any Python environment that supports GUI windows.

1. Why this tutorial is so nice

  • It’s visual — people love seeing code create art.
  • It’s short but expandable — readers can experiment with shapes, colors, and patterns.
  • It uses only standard library modules — no installation needed.

2. The Final Output

A hypnotic, rainbow-colored spirograph made of circles overlapping at different angles.


3. The Code

import turtle
import colorsys

def draw_spirograph(size_of_gap, num_colors=36):
    turtle.bgcolor("black")
    turtle.speed("fastest")
    turtle.hideturtle()

    # Create a list of rainbow colors
    colors = [colorsys.hsv_to_rgb(i/num_colors, 1, 1) for i in range(num_colors)]
    colors = [(int(r*255), int(g*255), int(b*255)) for r, g, b in colors]

    # Enable RGB mode
    turtle.colormode(255)

    for i in range(int(360 / size_of_gap)):
        turtle.pencolor(colors[i % num_colors])
        turtle.circle(100)
        turtle.setheading(turtle.heading() + size_of_gap)

if __name__ == "__main__":
    draw_spirograph(5)
    turtle.done()

4. How It Works

  1. colorsys.hsv_to_rgb
    Generates evenly spaced hues on the color wheel for smooth rainbow transitions.
  2. turtle.colormode(255)
    Allows us to use RGB values from 0–255 instead of the default 0–1 floats.
  3. The loop
    Draws a circle, then rotates the heading by a fixed size_of_gap degrees before drawing the next circle. This creates the spirograph effect.
  4. Speed
    turtle.speed("fastest") makes rendering almost instant.

5. Try This

  • Change size_of_gap to 10, 15, or 20 for different patterns.
  • Change turtle.circle(100) to a smaller or larger radius.
  • Experiment with num_colors for more or fewer hues.
  • Randomize colors instead of using a rainbow for a chaotic style.

6. Why readers will love it

  • They can run it immediately with no setup.
  • It produces satisfying visual results quickly.
  • It encourages playful experimentation.

If you want, I can also prepare:

  • A GIF preview of the drawing process for the blog post.
  • A “Next Steps” section showing how to add keyboard controls to change patterns live.

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Previous Post

Next Post

Loading Next Post...
Loading

Signing-in 3 seconds...