python绘画圣诞树
时间: 2023-12-13 19:33:25 浏览: 91
以下是绘制圣诞树的Python代码示例:
```python
import turtle
import random
# 设置画笔
tree = turtle.Turtle()
tree.speed(0)
turtle.bgcolor("white")
tree.color("green")
# 绘制树干
def draw_trunk():
tree.color("brown")
tree.pensize(20)
tree.penup()
tree.goto(0, -200)
tree.pendown()
tree.goto(0, -100)
# 绘制树叶
def draw_triangle(length):
tree.color("green")
tree.begin_fill()
tree.forward(length)
tree.left(120)
tree.forward(length)
tree.left(120)
tree.forward(length)
tree.end_fill()
# 绘制树
def draw_tree(height):
tree.penup()
tree.goto(0, -100)
tree.pendown()
tree.left(90)
for i in range(height):
draw_triangle(20 * (i + 1))
tree.penup()
tree.right(120)
tree.forward(20)
tree.left(120)
tree.pendown()
# 绘制装饰物
def draw_decorations(height):
colors = ["red", "blue", "yellow", "purple", "orange"]
for i in range(height):
for j in range(i + 1):
tree.penup()
tree.goto(-20 * i + 40 * j, -100 + 20 * i)
tree.pendown()
tree.color(random.choice(colors))
tree.begin_fill()
tree.circle(10)
tree.end_fill()
# 绘制完整的圣诞树
def draw_christmas_tree(height, decorations):
draw_tree(height)
# Position the turtle for drawing decorations
tree.left(90)
tree.goto(0, height * 20)
tree.right(90)
draw_decorations(decorations)
# 调用函数绘制圣诞树
draw_trunk()
draw_christmas_tree(10, 50)
# 隐藏画笔
tree.hideturtle()
# 显示绘制结果
turtle.done()
```
阅读全文