我正在用 Python 乌龟制作交通灯,在序列结束时,我希望所有的灯都闪烁黄色 [英] I am making a traffic light with Python turtle and at the end of the sequence I want all the lights to blink yellow

查看:43
本文介绍了我正在用 Python 乌龟制作交通灯,在序列结束时,我希望所有的灯都闪烁黄色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.我想要的只是让三只海龟同时移动/闪烁就像一个坏掉的红绿灯.我不知道该怎么做.如果您想查看我的所有代码,请通过答案告诉我.

This is my code. All I want is for three turtles to move/blink at the same time like a broken traffic light. I can't figure out how to do it. If you want to see all of my code, let me know by an answer.

#flash
speed(20)
#pens
pen1 = Turtle()
pen2 = Turtle()
pen3 = Turtle()
#loop
def loop():

while True:
    pen1.penup()
    pen1.color('yellow')
    pen1.goto(0,90)
    pen1.begin_fill()
    pen1.pendown()
    pen1.circle(40)
    pen1.penup()
    pen1.end_fill()
    pen1.color('black')
    time.sleep(1)
    pen1.begin_fill()
    pen1.pendown()
    pen1.circle(40)
    pen1.penup()
    pen1.end_fill()
    time.sleep(1)
while True:
    pen2.penup()
    pen2.color('yellow')
    pen2.goto(0,-140)
    pen2.begin_fill()
    pen2.pendown()
    pen2.circle(40)
    pen2.penup()
    pen2.end_fill()
    pen2.color('black')
    time.sleep(1)
    pen2.begin_fill()
    pen2.pendown()
    pen2.circle(40)
    pen2.penup()
    pen2.end_fill()
    time.sleep(1)



return loop()

推荐答案

这里有一个基于两个关键点的解决方案:首先,海龟不用于绘制交通灯,海龟交通灯;其次,我们使用turtle中的ontimer事件来控制闪烁:

Here's a solution based on two key points: first, the turtles aren't used to draw the traffic lights, the turtles are the traffic lights; second, we use the ontimer event in turtle to control the blinking:

from turtle import Turtle, Screen

CURSOR_SIZE = 20

def blink():
    for turtle in screen.turtles():
        turtle.fillcolor('yellow' if turtle.fillcolor() == 'black' else 'black')

    screen.ontimer(blink, 1000)

screen = Screen()

pen1 = Turtle(shape='circle')
pen1.shapesize(80 / CURSOR_SIZE)
pen1.color('black', 'yellow')
pen1.penup()
pen1.sety(90)

pen2 = pen1.clone()
pen2.sety(0)

pen3 = pen1.clone()
pen3.sety(-90)

blink()

screen.mainloop()

这篇关于我正在用 Python 乌龟制作交通灯,在序列结束时,我希望所有的灯都闪烁黄色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆