import turtle
turtle.speed(0)
# 绘制灯箱
turtle.pensize(5)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
# 绘制第一个灯,红灯
turtle.penup()
turtle.goto(50,200-35)
turtle.pendown()
turtle.dot(50,"red")
# 绘制第二个灯,黄灯
turtle.penup()
turtle.goto(50,200-95)
turtle.pendown()
turtle.dot(50,"yellow")
# 绘制第三个灯,绿灯
turtle.penup()
turtle.goto(50,200-155)
turtle.pendown()
turtle.dot(50,"green")
# 写字
turtle.penup()
turtle.goto(0,-60)
turtle.pendown()
turtle.write("交通灯",font=("Arial",20,"normal"))
turtle.hideturtle()
turtle.done()
继续优化,可以加上倒计时,模拟十字路口,红灯停绿灯行黄灯等一等的效果
import turtle
import time
turtle.speed(0)
turtle.hideturtle()
# 写字
turtle.penup()
turtle.goto(0,-60)
turtle.pendown()
turtle.write("交通灯",font=("Arial",20,"normal"))
turtle.penup()
turtle.goto(0,0)
turtle.pendown()
# 绘制灯箱
turtle.pensize(5)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(200)
turtle.left(90)
# 绘制第一个灯,红灯
turtle.penup()
turtle.goto(50,200-35)
turtle.pendown()
turtle.dot(50,"red")
# 等待5秒,红灯灭
time.sleep(5)
turtle.penup()
turtle.goto(50,200-35)
turtle.pendown()
turtle.dot(50,"white")
# 绘制第二个灯,黄灯
turtle.penup()
turtle.goto(50,200-95)
turtle.pendown()
turtle.dot(50,"yellow")
# 等待2秒,黄灯灭
time.sleep(3)
turtle.penup()
turtle.goto(50,200-95)
turtle.pendown()
turtle.dot(50,"white")
# 绘制第三个灯,绿灯
turtle.penup()
turtle.goto(50,200-155)
turtle.pendown()
turtle.dot(50,"green")
turtle.done()