Christmas Tree in Python Turtle
Intermediate · Festivals · 111 lines · draws in about 15 seconds
This program draws a Christmas tree from three stacked triangles, then decorates it with ornaments from a list, a gold star and presents under a snowy sky.

How the code works
Layers of the tree
Each layer is a triangle standing on the line y = base_y, centred on x = 0. Three calls with narrower, higher triangles stack into a tree.
def triangle(base_y, width, height, color): """One layer of the tree: a triangle standing on y = base_y.""" t.penup() t.goto(-width / 2, base_y) t.pendown() t.color(color) t.begin_fill() t.goto(width / 2, base_y) t.goto(0, base_y + height) t.goto(-width / 2, base_y) t.end_fill()
Presents from rectangles
A present is three rectangles: the box and two thin ribbon strips across the middle. Two dots on top make the bow.
def present(x, y, size, box_color, ribbon_color): """A square present with a ribbon both ways and a bow on top.""" rectangle(x, y, size, size, box_color) rectangle(x + size / 2 - 4, y, 8, size, ribbon_color) rectangle(x, y + size / 2 - 4, size, 8, ribbon_color) t.penup() t.goto(x + size / 2 - 8, y + size + 6) t.dot(16) t.goto(x + size / 2 + 8, y + size + 6) t.dot(16)
Snow in random places
random.randint() picks a place and a size for each of 60 flakes. random.seed(25) at the top makes the same numbers come out on every run, so the picture never changes.
for flake in range(60): t.goto(random.randint(-300, 300), random.randint(-180, 215)) t.dot(random.randint(3, 7), "white")
Ornaments that take turns
enumerate() numbers the ornaments 0, 1, 2 and so on, and number % len(colors) turns that number into a place in the colour list, so the colours repeat in order.
for number, (x, y) in enumerate(ornaments): t.goto(x, y) t.dot(18, colors[number % len(colors)])
Make it yours
Change the code above and press Run. Some ideas:
- Add more ornaments by adding (x, y) pairs to the
ornamentslist, for example(0, 0). - Change
range(60)torange(200)for a heavier snowfall. - Add a fourth present with
present(30, -205, 45, "darkorange", "white")beforet.hideturtle().
What it uses
- functions with parameters
- lists of tuples
- random with a seed
- enumerate and %
Every turtle command the site supports is listed on Python turtle online.