pythonturtle画圣诞树
时间: 2023-05-04 10:04:29 浏览: 128
使用Python语言中的turtle库,可以轻松地画出圣诞树。首先,需要导入turtle库和time库,并创建一个画布对象和画笔对象,代码如下所示:
```
import turtle
import time
canvas = turtle.Screen()
canvas.bgcolor("black")
pen = turtle.Turtle()
pen.speed(0)
pen.pensize(3)
pen.color("white")
```
接着,画出树干部分。树干部分可以直接使用turtle库的forward和right函数进行绘制,代码如下所示:
```
pen.penup()
pen.setpos(0, -150)
pen.pendown()
pen.forward(30)
pen.right(90)
pen.forward(40)
pen.right(90)
pen.forward(30)
```
然后,画出树叶部分。树叶部分可以使用循环结构进行重复绘制,代码如下所示:
```
pen.color("green")
pen.penup()
pen.setpos(-100, -110)
pen.pendown()
level = 9
branch_angle = 22
branch_length = 120
for i in range(level):
pen.left(branch_angle)
pen.forward(branch_length)
pen.right(2 * branch_angle)
pen.forward(branch_length)
pen.left(branch_angle - 5)
branch_length -= 10
```
最后,画出圣诞树的星星和彩灯。代码如下所示:
```
pen.color("yellow")
pen.penup()
pen.setpos(20, 90)
pen.pendown()
for i in range(5):
pen.forward(40)
pen.right(144)
pen.color("red")
pen.penup()
pen.setpos(-120, -105)
pen.pendown()
for i in range(5):
pen.forward(10)
pen.penup()
pen.forward(10)
pen.pendown()
time.sleep(5)
canvas.bye()
```
最后,加上一段sleep时间之后就能看到画出来的圣诞树画面了。
阅读全文