使用turtle库可以很方便地绘制圣诞树,下面是一个示例代码:
import turtle def draw_triangle(size): turtle.begin_fill() for _ in range(3): turtle.forward(size) turtle.left(120) turtle.end_fill() def draw_tree(size, level): if level == 0: turtle.color("green") draw_triangle(size) turtle.color("black") else: turtle.color("brown") turtle.forward(size/2) turtle.right(30) draw_tree(size/2, level-1) turtle.left(30) turtle.backward(size/2) turtle.right(60) draw_tree(size/2, level-1) turtle.left(60) turtle.backward(size/2) turtle.right(30) turtle.color("green") draw_triangle(size) def draw_star(size): turtle.color("yellow") turtle.begin_fill() for _ in range(5): turtle.forward(size) turtle.right(144) turtle.end_fill() # 设置画布大小和背景色 turtle.setup(800, 600) turtle.bgcolor("white") # 移动到树的底部中心位置 turtle.penup() turtle.goto(0, -250) turtle.pendown() # 绘制圣诞树 draw_tree(200, 4) # 移动到星星的位置 turtle.penup() turtle.goto(0, 0) turtle.pendown() # 绘制星星 draw_star(50) # 隐藏画笔 turtle.hideturtle() turtle.done()
运行以上代码,即可在turtle图形窗口中看到绘制的圣诞树和星星。