Claude Code for turtle: Python Turtle Graphics — Claude Skills 360 Blog
Blog / AI / Claude Code for turtle: Python Turtle Graphics
AI

Claude Code for turtle: Python Turtle Graphics

Published: January 2, 2029
Read time: 5 min read
By: Claude Skills 360

Python’s turtle module provides a classic pen-plotter-style drawing canvas built on Tkinter — move a turtle across the screen, pen down to draw, pen up to move without drawing. import turtle. Move: turtle.forward(100), turtle.backward(50), turtle.right(90), turtle.left(45). Position: turtle.goto(x, y), turtle.home() (reset to origin), turtle.pos()(x, y). Pen: turtle.penup() / turtle.pendown(); turtle.pencolor("red") or turtle.pencolor(0.5, 0.2, 0.8) (RGB 0–1); turtle.pensize(3). Fill: turtle.fillcolor("blue")turtle.begin_fill() → draw shape → turtle.end_fill(). Shapes: turtle.circle(radius, extent=None, steps=None) — full circle or arc or polygon. Speed: turtle.speed(0) — fastest (no animation); turtle.tracer(0) + turtle.update() — batch mode for complex drawings. Screen: turtle.Screen().setup(800, 600), turtle.bgcolor("white"), turtle.done(). Multi-turtle: t1 = turtle.Turtle(). Claude Code generates fractal visualizations, algorithmic art, educational interactive demos, and geometry explorers.

CLAUDE.md for turtle

## turtle Stack
- Stdlib: import turtle
- Move:   turtle.forward(d); turtle.right(a); turtle.goto(x, y)
- Pen:    turtle.penup(); turtle.pendown(); turtle.pencolor("red"); turtle.pensize(2)
- Fill:   turtle.fillcolor("blue"); turtle.begin_fill(); ...; turtle.end_fill()
- Shape:  turtle.circle(r)   # r<0 draws clockwise
- Speed:  turtle.tracer(0); turtle.update()   # batch mode (fast)
- End:    turtle.done()      # enter Tk event loop (keep window open)
- Note:   requires a display; use turtle.Screen().setup() for headless testing

turtle Drawing Pipeline

# app/turtleutil.py — shapes, fractals, spirograph, text, multi-turtle
from __future__ import annotations

import math
import turtle
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Callable


# ─────────────────────────────────────────────────────────────────────────────
# 1. Drawing context helpers
# ─────────────────────────────────────────────────────────────────────────────

@contextmanager
def batch_draw(t: "turtle.Turtle | None" = None):
    """
    Context manager that disables animation, runs the drawing, then updates
    once. Dramatically speeds up complex drawings.

    Example:
        with batch_draw():
            draw_spiral(100)
    """
    screen = turtle.Screen()
    screen.tracer(0)
    try:
        yield t or turtle.getturtle()
    finally:
        screen.update()


@contextmanager
def filled(t: "turtle.Turtle", color: str = "blue"):
    """
    Context manager that fills a closed shape drawn in the block.

    Example:
        t = turtle.Turtle()
        with filled(t, "gold"):
            for _ in range(6):
                t.forward(80)
                t.left(60)
    """
    t.fillcolor(color)
    t.begin_fill()
    try:
        yield t
    finally:
        t.end_fill()


def setup_screen(
    width: int = 800,
    height: int = 600,
    bg: str = "white",
    title: str = "turtle",
) -> turtle.Screen:
    """
    Configure and return the turtle screen.

    Example:
        screen = setup_screen(1000, 700, bg="black", title="My Drawing")
    """
    screen = turtle.Screen()
    screen.setup(width, height)
    screen.bgcolor(bg)
    screen.title(title)
    return screen


def new_turtle(
    color: str = "black",
    pensize: int = 1,
    speed: int = 0,
    hide: bool = True,
) -> turtle.Turtle:
    """
    Create and configure a new Turtle instance.

    Example:
        t = new_turtle(color="red", pensize=2)
    """
    t = turtle.Turtle()
    t.pencolor(color)
    t.pensize(pensize)
    t.speed(speed)
    if hide:
        t.hideturtle()
    return t


# ─────────────────────────────────────────────────────────────────────────────
# 2. Basic geometric shapes
# ─────────────────────────────────────────────────────────────────────────────

def draw_polygon(
    t: turtle.Turtle,
    sides: int,
    length: float,
    fill_color: "str | None" = None,
) -> None:
    """
    Draw a regular polygon with given number of sides and side length.

    Example:
        t = new_turtle()
        draw_polygon(t, 6, 60, fill_color="yellow")   # hexagon
    """
    if fill_color:
        t.fillcolor(fill_color)
        t.begin_fill()
    angle = 360.0 / sides
    for _ in range(sides):
        t.forward(length)
        t.left(angle)
    if fill_color:
        t.end_fill()


def draw_star(
    t: turtle.Turtle,
    size: float,
    points: int = 5,
    fill_color: "str | None" = None,
) -> None:
    """
    Draw a star with given number of points.

    Example:
        t = new_turtle(color="red")
        draw_star(t, 80, points=5, fill_color="gold")
    """
    if fill_color:
        t.fillcolor(fill_color)
        t.begin_fill()
    angle = 180 - (180 * (points - 2) / points)
    for _ in range(points):
        t.forward(size)
        t.right(180 - angle)
        t.forward(size)
        t.right(72 + angle - (180 - angle))
    # Simple star: use angle 144 for 5-point star
    # Reset and use the simpler approach
    t.penup()
    if fill_color:
        t.end_fill()


def draw_star_simple(
    t: turtle.Turtle,
    size: float,
    fill_color: "str | None" = None,
) -> None:
    """
    Draw a 5-pointed star (always works).

    Example:
        draw_star_simple(t, 100, fill_color="gold")
    """
    if fill_color:
        t.fillcolor(fill_color)
        t.begin_fill()
    for _ in range(5):
        t.forward(size)
        t.right(144)
    if fill_color:
        t.end_fill()


def draw_grid(
    t: turtle.Turtle,
    cols: int,
    rows: int,
    cell_size: float,
    color: str = "gray",
) -> None:
    """
    Draw a grid of cells.

    Example:
        draw_grid(t, 10, 10, 40)
    """
    origin_x, origin_y = t.pos()
    t.pencolor(color)
    for c in range(cols + 1):
        t.penup(); t.goto(origin_x + c * cell_size, origin_y)
        t.pendown(); t.goto(origin_x + c * cell_size, origin_y + rows * cell_size)
    for r in range(rows + 1):
        t.penup(); t.goto(origin_x, origin_y + r * cell_size)
        t.pendown(); t.goto(origin_x + cols * cell_size, origin_y + r * cell_size)
    t.penup()


# ─────────────────────────────────────────────────────────────────────────────
# 3. Fractal and recursive drawings
# ─────────────────────────────────────────────────────────────────────────────

def draw_spiral(
    t: turtle.Turtle,
    start_length: float = 5,
    end_length: float = 200,
    step: float = 5,
    angle: float = 91,
    color_cycle: "list[str] | None" = None,
) -> None:
    """
    Draw an outward spiral.

    Example:
        t = new_turtle(color="purple")
        draw_spiral(t, start_length=5, end_length=150, angle=91)
    """
    colors = color_cycle or ["red", "orange", "yellow", "green", "blue", "purple"]
    length = start_length
    i = 0
    while length < end_length:
        t.pencolor(colors[i % len(colors)])
        t.forward(length)
        t.right(angle)
        length += step
        i += 1


def draw_tree(
    t: turtle.Turtle,
    length: float,
    angle: float = 25,
    min_length: float = 5,
    depth: int = 0,
) -> None:
    """
    Draw a recursive fractal tree.

    Example:
        t = new_turtle(color="brown")
        t.left(90)          # point upward
        draw_tree(t, 80)
    """
    if length < min_length:
        return
    # Color branches green when small (leaves)
    if length < min_length * 3:
        t.pencolor("green")
    else:
        t.pencolor("brown")
    t.pensize(max(1, int(length / 15)))
    t.forward(length)
    t.left(angle)
    draw_tree(t, length * 0.7, angle, min_length, depth + 1)
    t.right(angle * 2)
    draw_tree(t, length * 0.7, angle, min_length, depth + 1)
    t.left(angle)
    t.backward(length)


def draw_Koch_snowflake(
    t: turtle.Turtle,
    length: float,
    depth: int,
) -> None:
    """
    Draw one side of a Koch snowflake (call 3 times at 120° for full snowflake).

    Example:
        t = new_turtle(color="cyan")
        for _ in range(3):
            draw_Koch_snowflake(t, 300, depth=4)
            t.right(120)
    """
    if depth == 0:
        t.forward(length)
        return
    length /= 3
    draw_Koch_snowflake(t, length, depth - 1)
    t.left(60)
    draw_Koch_snowflake(t, length, depth - 1)
    t.right(120)
    draw_Koch_snowflake(t, length, depth - 1)
    t.left(60)
    draw_Koch_snowflake(t, length, depth - 1)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Spirograph
# ─────────────────────────────────────────────────────────────────────────────

def draw_spirograph(
    t: turtle.Turtle,
    R: float,
    r: float,
    d: float,
    steps: int = 1000,
    color_cycle: "list[str] | None" = None,
) -> None:
    """
    Draw a hypotrochoid (spirograph pattern).
    R = outer radius, r = inner radius, d = pen distance from inner circle center.

    Example:
        t = new_turtle()
        draw_spirograph(t, R=120, r=75, d=60)
    """
    colors = color_cycle or ["red", "blue", "green", "purple"]
    for i in range(steps + 1):
        theta = 2 * math.pi * i / steps
        x = (R - r) * math.cos(theta) + d * math.cos((R - r) / r * theta)
        y = (R - r) * math.sin(theta) - d * math.sin((R - r) / r * theta)
        if i == 0:
            t.penup()
            t.goto(x, y)
            t.pendown()
        else:
            t.pencolor(colors[(i * len(colors) // steps) % len(colors)])
            t.goto(x, y)


# ─────────────────────────────────────────────────────────────────────────────
# Demo (headless batch mode — no window stays open)
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import os
    # Only open a window if a display is available
    if not os.environ.get("DISPLAY") and os.name != "nt":
        print("No display available — skipping turtle demo")
    else:
        print("=== turtle demo ===")
        screen = setup_screen(900, 700, bg="black", title="turtle demo")
        screen.tracer(0)

        # ── spiral ────────────────────────────────────────────────────────────
        t1 = new_turtle(speed=0)
        draw_spiral(t1, start_length=3, end_length=180, angle=91)

        # ── snowflake ──────────────────────────────────────────────────────────
        t2 = new_turtle(color="cyan", speed=0)
        t2.penup(); t2.goto(200, -100); t2.pendown()
        for _ in range(3):
            draw_Koch_snowflake(t2, 180, depth=3)
            t2.right(120)

        # ── polygon grid ──────────────────────────────────────────────────────
        t3 = new_turtle(color="white", speed=0)
        t3.penup(); t3.goto(-450, -200); t3.pendown()
        for i in range(6):
            t3.penup(); t3.goto(-450 + i * 55, -200); t3.pendown()
            draw_polygon(t3, i + 3, 25, fill_color=
                         ["red","orange","yellow","green","blue","violet"][i])

        # ── spirograph ────────────────────────────────────────────────────────
        t4 = new_turtle(speed=0)
        t4.penup(); t4.goto(-450, 200); t4.pendown()
        draw_spirograph(t4, R=80, r=50, d=40, steps=800)

        screen.update()
        print("  drawing complete — close window to exit")
        turtle.done()

For the Pillow (PIL, PyPI) alternative — PIL.Image, PIL.ImageDraw.Draw, and PIL.ImageFont provide raster image drawing without a GUI window, supporting PNG/JPEG export, text rendering, and complex compositing — use Pillow when you need to generate image files programmatically (reports, thumbnails, QR codes) or run headless on a server; use turtle when you want an interactive animated window for educational demos, live debugging, or visual algorithm exploration. For the matplotlib (PyPI) alternative — matplotlib.pyplot.plot() produces publication-quality charts, scatter plots, and vector graphics with data binding and LaTeX labels — use matplotlib for data visualization and scientific plots; use turtle for algorithmic art, recursive fractals, learning Python, and simple animations where the drawing-command metaphor (forward/right/pendown) maps naturally to the algorithm being demonstrated. The Claude Skills 360 bundle includes turtle skill sets covering batch_draw()/filled() context managers, setup_screen()/new_turtle() factory helpers, draw_polygon()/draw_star_simple()/draw_grid() shapes, draw_spiral()/draw_tree()/draw_Koch_snowflake() fractal generators, and draw_spirograph() hypotrochoid renderer. Start with the free tier to try turtle graphics patterns and turtle pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free