python画图樱花树
时间: 2023-06-21 16:06:03 浏览: 79
python画樱花树
以下是一个简单的 Python 代码,用于绘制樱花树:
```python
import turtle
import random
# 设置画布大小
turtle.setup(width=800, height=600)
# 隐藏海龟
turtle.hideturtle()
# 定义花瓣颜色
COLORS = ["pink", "lightpink", "hotpink", "deeppink", "palevioletred", "mediumvioletred"]
# 定义花瓣数量
PETALS_NUM = 15
# 定义花瓣大小
PETALS_SIZE = 30
# 定义花瓣下落速度
PETALS_SPEED = 1
# 定义枝干长度
TRUNK_LENGTH = 100
# 定义枝干角度
TRUNK_ANGLE = 30
# 定义枝干粗细
TRUNK_WIDTH = 10
# 定义树干颜色
TRUNK_COLOR = "brown"
# 定义花瓣形状
def petal():
turtle.begin_fill()
turtle.circle(PETALS_SIZE)
turtle.end_fill()
# 绘制花瓣
def petals():
for i in range(PETALS_NUM):
turtle.penup()
x = random.randint(-200, 200)
y = random.randint(100, 200)
turtle.goto(x, y)
turtle.pendown()
turtle.color(random.choice(COLORS))
petal()
# 绘制枝干
def trunk(length):
if length > 0:
turtle.pensize(length / TRUNK_WIDTH)
turtle.forward(length)
turtle.right(TRUNK_ANGLE)
trunk(length - PETALS_SPEED)
turtle.left(2 * TRUNK_ANGLE)
trunk(length - PETALS_SPEED)
turtle.right(TRUNK_ANGLE)
turtle.backward(length)
# 设置画笔属性
turtle.speed(0)
turtle.color(TRUNK_COLOR)
# 绘制樱花树
turtle.left(90)
trunk(TRUNK_LENGTH)
petals()
# 点击关闭窗口
turtle.exitonclick()
```
运行以上代码,就可以在画布上看到一棵粉色的樱花树了。你可以根据自己的喜好调整一些参数,例如花瓣数量、大小、下落速度等等,让樱花树变得更加美丽。
阅读全文