Python 聖誕樹程式碼
三層樹葉、彩燈、樹頂的星星和滿天的雪。點數字改層數和彩燈,改好了帶走送人。
完整程式碼(69 行)
import turtle
import random
screen = turtle.Screen()
screen.bgcolor("midnightblue")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
def triangle(bottom, width, color):
# 一層樹葉:底邊在 bottom,寬 width
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()
# 樹幹
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()
# 三層樹葉,一層比一層小
layers = 3
for i in range(layers):
triangle(-150 + i * 95, 340 - i * 85, "forestgreen")
# 彩燈:掛在每一層裡面
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))
# 樹頂的星星
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()
# 雪
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("聖誕快樂!", align="center", font=("Arial", 28, "bold"))怎麼畫的
每層樹葉是一個填色的三角形:triangle(底邊的高度, 寬度, 顏色) 用 begin_fill() 和 end_fill() 把走過的三條邊圍起來塗滿。
三層樹葉用一個 for 迴圈畫:每往上一層,底邊高 95、寬度少 85,所以越往上越窄。
彩燈要掛在三角形裡面:先隨機一個高度 h,算出這個高度上三角形有多寬(half),再在這個寬度裡隨機一個位置點一個圓點。
最後用 t.write("聖誕快樂!", align="center", font=("Arial", 28, "bold")) 在下面寫字,align="center" 讓字以海龜的位置為中心。
常見問題
怎麼把「聖誕快樂」改成別的字或名字?
點「改一改」,進線上編程把 write 括號裡的字換掉再執行。注意引號和括號要用英文的。
在自己電腦上執行,視窗一閃就沒了?
在程式碼最後加一行 turtle.done(),視窗就會停住直到你關掉它。
星星為什麼中間是空的?
turtle 填充用的是「奇偶規則」:五角星中間那塊被邊圍了兩次,就不塗色。真 Python 裡也是這樣,這一頁畫的和它一樣。

雪花科赫曲線:越折越細的邊
跨年煙花會動的煙花:一幀一幀畫
滿天星漸變夜空和會閃的星星
愛心表白兩段半圓拼成的心