Python Turtle drawing from entry to advanced

Turtle graphics is Python's built-in "interactive drawing toy library", derived from the programming learning tool designed by Seymour Papert and Wally Feurzig in 1966 for the LOGO language. It draws graphics by controlling a virtual "little turtle with a paintbrush" to move on the screen - it can be used as a bridge for entry-level programming, or it can also be used to play fractals, geometric art or even simple interactive games.

1. Starting from scratch: basic drawing operations

1.1 First draw a rectangle with colored edges to warm up.

First run the most intuitive code to get familiar with itturtleThe most core commands:

from turtle import *

# 初始化画布和画笔配置
setup(600, 400)  # 弹出宽600px、高400px的窗口
width(4)         # 画笔线条粗细设为4
speed(3)         # 绘制速度调为3(适中)

# 逐边绘制彩色长方形
pencolor('red')   # 第一条边:红色
forward(200)      # 小海龟前进200像素
right(90)         # 原地向右转90度

pencolor('green') # 第二条边:绿色
forward(100)
right(90)

pencolor('blue')  # 第三条边:蓝色
forward(200)
right(90)

pencolor('black') # 第四条边:黑色
forward(100)

done()  # 绘制完成后保持窗口不关闭

This piece of code demonstratesforwardrightpencolorWaiting for the core command, the turtle first walks a long red edge to the right, turns 90° and then draws a short green edge, completing a circle in sequence, and finally gets a rectangle with a colored border.

1.2 Common command cheat sheet

Organize the commands that have been used just now and will be used frequently in the future into a table for easy reference at any time:

CommandDescriptionSample Code
forward(distance) / fd(d)The little turtle advances the specified pixels toward the current directionfd(100)
backward(distance) / bk(d)The little turtle moves backward by the specified pixel in the opposite direction to its current orientationbk(50)
right(angle) / rt(a)Turn right on the spot to specify the anglert(90)
left(angle) / lt(a)Turn left on the spot to specify the anglelt(45)
penup() / pu()Lift the brush and move it without leaving a tracepu()
pendown() / pd()Put down the brush and start drawing lines as you movepd()
pencolor(color) / pencolor(r,g,b)Set brush color (supports English/Hex/RGB)pencolor('skyblue')
fillcolor(color)Set fill color (needs andbegin_fill()/end_fill()Cooperation)fillcolor('yellow')
width(size) / pensize(s)Set brush line thicknesspensize(6)
speed(s)Drawing speed: 0 fastest/1-10 increment (default 6)speed(0)
goto(x,y)Move directly to the specified coordinates of the canvas (the origin is in the middle)goto(0, -100)
setheading(angle) / seth(a)Reset the direction of the little turtle (0 to the right/90 up/180 left/270 down)seth(90)

2. Improve efficiency: draw complex graphics with loops and recursion

2.1 Use loops to draw a neat row of five-pointed stars

It is too troublesome to write the code to draw the corners 5 times line by line. UseforThe loop is optimized into a general function:

from turtle import *

def draw_star(x, y, size=40):
    """在(x,y)坐标处画指定大小的五角星"""
    penup()
    goto(x, y)
    pendown()
    
    setheading(0)  # 先把小海龟朝向右边
    for _ in range(5):
        forward(size)
        right(144)  # 五角星外角度数固定144°

# 画从左到右的9个五角星(间距50px)
title("一排小五角星")
for x_pos in range(-200, 250, 50):
    draw_star(x_pos, 0, size=30)

done()

With loops, the boring job of repeatedly moving turtles is left tofor, you just set the coordinates and size, and easily draw a neat row of five-pointed stars.

2.2 Use recursion to draw a gradient fractal tree

Fractal is a classic way of playing turtle, and recursion can perfectly realize the branches of "self-similar structure":

from turtle import *
import random

# 初始化配置(先运行配置再画图)
colormode(255)  # 切换到RGB颜色模式(0-255)
speed(0)        # 最快绘制速度
left(90)        # 小海龟初始朝上
penup()
goto(0, -180)   # 把树干底部移到画布下方
pendown()

# 分形树核心参数
TREE_LEVELS = 10    # 递归深度(越深越密,别超过15)
BRANCH_LENGTH = 80  # 初始树干长度
BRANCH_ANGLE = 25   # 左右分支的基础夹角

def draw_branch(length, level):
    """递归绘制树枝的函数"""
    if level > TREE_LEVELS:
        return
    
    # 树枝宽度和颜色随深度变化:越往上越细越浅
    width(TREE_LEVELS - level + 1)
    green_level = 255 // TREE_LEVELS * level
    pencolor(0, green_level, 0)
    
    forward(length)
    
    # 先画右分支,再画左分支,最后退回去
    right(BRANCH_ANGLE + random.randint(-5, 5))  # 加随机角度让树更自然
    draw_branch(length * 0.75, level + 1)
    
    left(BRANCH_ANGLE * 2 + random.randint(-5, 5))
    draw_branch(length * 0.75, level + 1)
    
    right(BRANCH_ANGLE + random.randint(-5, 5))
    backward(length)

# 开始绘制
title("带随机感的渐变分形树")
draw_branch(BRANCH_LENGTH, 1)
hideturtle()  # 画完把小海龟藏起来更美观

done()

After running, you will see a tree that changes from thick to thin, from dark green to light green, with random disturbances every time it bifurcates left and right, making it look more natural. This is the magic of recursion.

3. Advanced gameplay: object-oriented, events and animation

Most of the original code uses the global function style, but modern Python recommends the object-oriented (OO) style - it can avoid conflicts when multiple turtles draw at the same time, and is more in line with engineering coding habits.

3.1 OO style painted colorful spiral

from turtle import Turtle, Screen

def main():
    # 1. 创建独立的画布和海龟对象
    screen = Screen()
    screen.setup(800, 600)
    screen.title("OO风格彩色螺旋")
    screen.bgcolor("#f0f8ff")  # 淡蓝色背景
    
    spiral_turtle = Turtle()
    spiral_turtle.shape("turtle")  # 把画笔图标换成可爱的小海龟
    spiral_turtle.color("purple")
    spiral_turtle.speed(0)
    spiral_turtle.pensize(2)
    
    # 2. 绘制彩色螺旋(颜色循环+角度微调制造缠绕感)
    colors = ['#ff4757', '#ffa502', '#2ed573', '#1e90ff', '#a55eea', '#ff6b81']
    for i in range(120):
        spiral_turtle.color(colors[i % 6])
        spiral_turtle.forward(i * 3)
        spiral_turtle.right(92)  # 比90°多2°,螺旋不会重叠
    
    spiral_turtle.hideturtle()
    screen.mainloop()

if __name__ == "__main__":
    main()

Here, the length of each step gradually increases, the colors change cyclically, and the angle slightly deviates from 90°, creating a gorgeous colorful spiral.

3.2 Event-driven: Use the keyboard to control the little turtle

In addition to automatic drawing, turtle also supports simple key interaction, which can make a real-time "small drawing board":

from turtle import Turtle, Screen

def move_forward():
    artist.forward(15)

def move_backward():
    artist.backward(15)

def turn_left():
    artist.left(20)

def turn_right():
    artist.right(20)

def clear_canvas():
    artist.clear()
    artist.penup()
    artist.home()
    artist.pendown()

def toggle_pen():
    if artist.isdown():
        artist.penup()
    else:
        artist.pendown()

# 初始化画布和海龟
screen = Screen()
screen.title("键盘控制的小画板")
screen.setup(700, 500)

artist = Turtle()
artist.shape("turtle")
artist.color("darkgreen")
artist.speed(5)

# 绑定按键与对应函数
screen.onkey(move_forward, "Up")
screen.onkey(move_backward, "Down")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
screen.onkey(clear_canvas, "c")
screen.onkey(toggle_pen, "space")

screen.listen()  # 关键一步:让画布开始监听键盘输入
screen.mainloop()

Press the arrow keys to control movement and steering, press space to raise/lower the brush, and press C to clear the canvas - this is a zero-dependency mini drawing tool.

4. Pitfalls and best practices for newbies

4.1 Pitfall avoidance guide

  1. forgetdone()ormainloop(): If it is a global function style, usedone();If it is OO style, useScreen().mainloop(), otherwise the window will crash.
  2. The coordinate origin is reversed: the turtle's coordinate origin is in the middle of the canvas, not the upper left corner (unlike most graphics libraries).
  3. Recursion depth is too large: For recursive graphics such as fractal trees and snowflakes, the depth should not exceed 15, otherwise it will throwRecursionError
  4. Multiple Turtle Conflicts: Be careful when using global functions, try to create independent ones in OO styleTurtleExample, to avoid brushes from interfering with each other.

4.2 Best Practices

  1. Modular code: Encapsulate complex graphics (such as flowers and trees) into functions or classes for easy reuse.
  2. Turn off automatic refresh acceleration: When drawing complex graphics, usescreen.tracer(0)Turn off automatic refresh and do it manually after drawingscreen.update(), the drawing speed can be increased dozens of times.
  3. usetry-finallyClosing: Ensure that no matter whether the code reports an error or not, the window can be closed normally or enter the event loop.
  4. Addhideturtle(): Hide the little turtle after painting to make the final pattern look cleaner.

  1. Python 官方 turtle 文档: The most complete and authoritative reference manual.
  2. Michael0x2a 的 Turtle 示例库: Collection of a lot of cool graphics codes.
  3. Real Python 的 Turtle 入门指南: With pictures and texts, it is suitable for people with no basic knowledge.

Although Turtle is simple, its upper limit is not low - you can use it to practice loops, recursion, object-oriented, and even develop simple snake and brick-breaking games. Open your Python editor and give it a try!