Python调用turtle库画彩色樱花树
时间: 2023-06-11 21:05:15 浏览: 128
可以使用以下代码实现:
```python
import turtle
import random
# 设置画布大小和背景颜色
canvas = turtle.Screen()
canvas.bgcolor("white")
canvas.setup(width=800, height=600)
# 定义画笔
pen = turtle.Turtle()
pen.speed(0)
pen.ht()
pen.up()
# 定义花瓣颜色列表
colors = ["pink", "lightpink", "deeppink", "hotpink", "palevioletred", "mediumvioletred"]
# 画樱花树
def draw_tree(branch_len):
if branch_len > 0:
if branch_len < 20:
# 画花瓣
pen.color(random.choice(colors))
pen.dot(random.randint(6, 10))
pen.forward(branch_len)
pen.right(20)
draw_tree(branch_len - 10)
pen.left(40)
draw_tree(branch_len - 10)
pen.right(20)
pen.backward(branch_len)
# 设置起始位置和角度
pen.goto(0, -250)
pen.left(90)
# 画树干
pen.pensize(10)
pen.color("brown")
pen.down()
pen.forward(100)
# 画树枝
draw_tree(60)
# 关闭画布
canvas.exitonclick()
```
运行结果:
![樱花树](https://img-blog.csdnimg.cn/20220104103349875.png#pic_center)
阅读全文