Python 使用 Turtle 库绘制圣诞树
前言
Python 的 turtle 模块是一个非常适合初学者学习图形化编程的工具。它通过控制画笔在屏幕上移动来绘制图形,支持递归、随机数等高级特性。本文将介绍如何使用 Python turtle 绘制一棵包含星星、彩灯、雪人和雪花的动态圣诞树。
环境准备
- 确保已安装 Python 3.x 版本。
- 无需额外安装第三方库,
turtle和random均为标准库。 - 推荐使用 PyCharm、VS Code 或 IDLE 作为开发工具。
代码逻辑分析
本程序主要包含以下几个核心部分:
- 初始化设置:设置画布大小、背景颜色、画笔速度和粗细。
- 五角星绘制:位于树顶,使用循环和角度计算完成。
- 递归树形结构:利用递归函数
tree(d, s)模拟树枝的生长,参数d控制深度,s控制长度。 - 随机装饰:包括彩灯(
drawlight)和底部装饰球,利用随机数生成位置和颜色。 - 雪人绘制:独立函数
drawsnowman,通过坐标定位绘制头部、身体及五官。 - 雪花效果:
drawsnow函数在屏幕随机位置绘制六角形雪花,营造冬日氛围。 - 文字显示:在画面顶部添加节日祝福文字。
完整源代码
import turtle as t
import random as r
# 初始化设置
t.speed(1000)
t.pensize(5)
t.screensize(800, 800, bg='black')
t.left(90)
t.forward(250)
# 定义画五角星的函数
n = 100.0
t.color("orange", "yellow")
t.begin_fill()
t.left(126)
for i in range(5):
t.forward(n / 5)
t.right(144)
t.forward(n / 5)
t.left(72)
t.end_fill()
t.right()
():
r.randint(, ) == :
t.color()
t.circle()
r.randint(, ) == :
t.color()
t.circle()
r.randint(, ) == :
t.color()
t.circle()
r.randint(, ) == :
t.color()
t.circle()
:
():
d <= :
t.forward(s)
tree(d - , s * )
t.right()
tree(d - , s * )
drawlight()
t.right()
tree(d - , s * )
t.right()
t.backward(s)
tree(, )
t.backward()
i ():
a = - * r.random()
b = - * r.random()
t.up()
t.forward(b)
t.left()
t.forward(a)
t.down()
r.randint(, ) == :
t.color()
:
t.color()
t.circle()
t.up()
t.backward(a)
t.right()
t.backward(b)
():
t.goto(n, m)
t.pencolor()
t.pensize()
t.fillcolor()
t.seth()
t.begin_fill()
t.circle(a)
t.end_fill()
t.seth()
t.begin_fill()
t.circle(b)
t.end_fill()
t.pencolor()
t.fillcolor()
t.penup()
t.goto(n-a/, m+a)
t.seth()
t.pendown()
t.begin_fill()
t.circle()
t.end_fill()
t.penup()
t.goto(n+a/, m+a)
t.seth()
t.pendown()
t.begin_fill()
t.circle()
t.end_fill()
t.penup()
t.goto(n, m+a/)
t.seth()
t.pendown()
t.fd()
t.penup()
t.pencolor()
t.fillcolor()
t.goto(n, m-b/)
t.pendown()
t.begin_fill()
t.circle()
t.end_fill()
t.penup()
t.pencolor()
t.fillcolor()
t.goto(n, m-b/)
t.pendown()
t.begin_fill()
t.circle()
t.end_fill()
t.penup()
t.pencolor()
t.fillcolor()
t.goto(n, m-(*b)/)
t.pendown()
t.begin_fill()
t.circle()
t.end_fill()
drawsnowman(-, -, , )
drawsnowman(-, -, , )
t.up()
t.goto(, )
t.down()
t.color(, )
t.penup()
t.write(, font=(, , ))
t.end_fill()
():
t.ht()
t.pensize()
i ():
t.pencolor()
t.pu()
t.setx(r.randint(-, ))
t.sety(r.randint(-, ))
t.pd()
dens =
snowsize = r.randint(, )
j (dens):
t.fd((snowsize))
t.backward((snowsize))
t.right(( / dens))
drawsnow()
t.done()


