python海龟绘图红绿灯
时间: 2023-12-23 18:28:40 浏览: 93
python海龟绘图word文档一百多道练习题教师教学与学生巩固运用好文档
5星 · 资源好评率100%
以下是使用Python海龟绘图库绘制红绿灯的示例代码:
```python
import turtle
import time
# 画出边框
turtle.width(20)
for i in range(2):
turtle.left(90)
turtle.fd(300)
turtle.left(90)
turtle.fd(150)
turtle.hideturtle() # 隐藏海龟
# 画红绿灯
turtle.penup()
turtle.goto(-75, 75) # 移动到红灯位置
turtle.pendown()
turtle.fillcolor("red")
turtle.begin_fill()
turtle.circle(75) # 画红灯圆
turtle.end_fill()
turtle.penup()
turtle.goto(-75, -75) # 移动到绿灯位置
turtle.pendown()
turtle.fillcolor("green")
turtle.begin_fill()
turtle.circle(75) # 画绿灯圆
turtle.end_fill()
turtle.penup()
turtle.goto(-75, 0) # 移动到黄灯位置
turtle.pendown()
turtle.fillcolor("yellow")
turtle.begin_fill()
turtle.circle(75) # 画黄灯圆
turtle.end_fill()
# 控制红绿灯状态
while True:
turtle.fillcolor("gray") # 灭灯
turtle.penup()
turtle.goto(-75, 75) # 移动到红灯位置
turtle.pendown()
turtle.begin_fill()
turtle.circle(75) # 画红灯圆
turtle.end_fill()
time.sleep(1)
turtle.fillcolor("red") # 红灯亮
turtle.penup()
turtle.goto(-75, 75) # 移动到红灯位置
turtle.pendown()
turtle.begin_fill()
turtle.circle(75) # 画红灯圆
turtle.end_fill()
time.sleep(3)
turtle.fillcolor("gray") # 灭灯
turtle.penup()
turtle.goto(-75, 0) # 移动到黄灯位置
turtle.pendown()
turtle.begin_fill()
turtle.circle(75) # 画黄灯圆
turtle.end_fill()
time.sleep(1)
turtle.fillcolor("green") # 绿灯亮
turtle.penup()
turtle.goto(-75, -75) # 移动到绿灯位置
turtle.pendown()
turtle.begin_fill()
turtle.circle(75) # 画绿灯圆
turtle.end_fill()
time.sleep(3)
```
阅读全文