Kodewick
Start learning →

Python Turtle Christmas Tree

Three layers of leaves, lights, a star on top and snow all around. Click a number to change it, then take it with you.

Python Turtle Christmas Tree
The full code (69 lines)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("midnightblue")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def triangle(bottom, width, color):
    # one layer of leaves: its bottom edge at `bottom`, `width` wide
    t.penup()
    t.goto(-width / 2, bottom)
    t.pendown()
    t.color(color)
    t.begin_fill()
    t.goto(width / 2, bottom)
    t.goto(0, bottom + width * 0.6)
    t.goto(-width / 2, bottom)
    t.end_fill()


# the trunk
t.penup()
t.goto(-22, -210)
t.color("saddlebrown")
t.begin_fill()
for side in [44, 60, 44, 60]:
    t.forward(side)
    t.left(90)
t.end_fill()

# three layers, each smaller than the one below
layers = 3
for i in range(layers):
    triangle(-150 + i * 95, 340 - i * 85, "forestgreen")

# lights: hung inside each layer
colors = ["red", "gold", "deepskyblue", "orange", "violet"]
for i in range(layers):
    bottom = -150 + i * 95
    width = 340 - i * 85
    for k in range(8):
        h = random.uniform(10, width * 0.6 - 12)
        half = width / 2 * (1 - h / (width * 0.6))
        t.penup()
        t.goto(random.uniform(-half + 8, half - 8), bottom + h)
        t.dot(12, random.choice(colors))

# the star on top
top = -150 + (layers - 1) * 95 + (340 - (layers - 1) * 85) * 0.6
t.goto(-18, top - 6)
t.setheading(0)
t.color("gold")
t.begin_fill()
for i in range(5):
    t.forward(36)
    t.right(144)
t.end_fill()

# snow
for i in range(80):
    t.goto(random.randint(-300, 300), random.randint(-280, 280))
    t.dot(random.randint(3, 6), "white")

t.goto(0, -275)
t.color("white")
t.write("Merry Christmas!", align="center", font=("Arial", 28, "bold"))

How it is drawn

Each layer of leaves is a filled triangle: triangle(bottom, width, color) walks its three sides between begin_fill() and end_fill(), and the shape is filled.

A for loop draws the layers: each one 95 higher and 85 narrower than the one below.

The lights must hang inside a triangle: pick a random height h, work out how wide the triangle is there (half), then put a dot somewhere within that width.

t.write("Merry Christmas!", align="center", font=("Arial", 28, "bold")) writes the greeting centred on the turtle.

Questions

How do I change the greeting or add a name?

Click Edit, change the text inside write(...) in the playground and run it again.

On my computer the window closes at once?

Add turtle.done() as the last line: the window then stays open until you close it.

Why is the middle of the star empty?

turtle (Tk) fills with the even-odd rule: the star's middle is enclosed twice, so it is left unfilled. Real Python does the same, and so does this page.

Try another