python初级turtle画樱花树
时间: 2023-08-29 15:07:02 浏览: 96
python画樱花树
好的,我可以回答这个问题。使用Python中的turtle库可以绘制樱花树,下面是一段示例代码:
```
import turtle
import random
# 设定画布大小和坐标系
canvas = turtle.Screen()
canvas.bgcolor("black")
canvas.setup(800, 600)
canvas.setworldcoordinates(0, 0, 800, 600)
# 定义樱花树的画笔
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# 定义樱花树的枝干
def tree_branch(length, thickness):
if length < 10:
return
pen.pensize(thickness)
pen.forward(length)
angle = random.randint(15, 45)
pen.right(angle)
tree_branch(length - random.randint(10, 20), thickness - 1)
pen.left(angle * 2)
tree_branch(length - random.randint(10, 20), thickness - 1)
pen.right(angle)
pen.backward(length)
# 定义樱花树的花朵
def tree_flower(size):
petals = random.randint(5, 15)
angle = 360 / petals
pen.fillcolor(random.choice(["pink", "lightpink", "hotpink", "deeppink"]))
pen.begin_fill()
for i in range(petals):
pen.forward(size)
pen.right(angle)
pen.forward(size)
pen.right(180 - angle)
pen.end_fill()
# 绘制樱花树
pen.penup()
pen.goto(400, 0)
pen.pendown()
pen.setheading(90)
pen.left(90 + random.randint(-15, 15))
tree_branch(100, 6)
for i in range(200):
pen.penup()
pen.goto(random.randint(0, 800), random.randint(50, 400))
pen.pendown()
tree_flower(random.randint(5, 20))
turtle.done()
```
希望对你有帮助!
阅读全文