Python编写一个红绿灯
时间: 2024-05-18 15:09:50 浏览: 21
好的,编写一个红绿灯可以使用Python中的turtle库来实现。下面是一个简单的红绿灯示例代码:
```
import turtle
import time
# 设置画笔
pen = turtle.Turtle()
pen.speed(0)
pen.penup()
pen.goto(0, -100)
# 设置红灯
def red_light():
pen.color('gray')
pen.fillcolor('red')
pen.begin_fill()
pen.circle(80)
pen.end_fill()
# 设置黄灯
def yellow_light():
pen.color('gray')
pen.fillcolor('yellow')
pen.begin_fill()
pen.circle(80)
pen.end_fill()
# 设置绿灯
def green_light():
pen.color('gray')
pen.fillcolor('green')
pen.begin_fill()
pen.circle(80)
pen.end_fill()
# 循环显示红灯和绿灯
while True:
red_light()
time.sleep(5)
yellow_light()
time.sleep(2)
green_light()
time.sleep(5)
yellow_light()
time.sleep(2)
```
这段代码会显示一个默认位于屏幕正中央的灯。程序会循环显示红灯、黄灯、绿灯、黄灯。其中,红灯和绿灯显示5秒,黄灯显示2秒。