我已经开始使用Python和Raspberry Pi,并试图使用它们进行一些物理计算。如何中断while循环,运行函数并返回循环
我从那开始:https://www.raspberrypi.org/learning/physical-computing-with-python/,一切都很顺利。
比我试图玩弄红绿灯(成功!): https://www.raspberrypi.org/learning/physical-computing-with-python/trafficlights/
这里我的代码:
from gpiozero import Button, TrafficLights
from time import sleep
lights = TrafficLights(25, 8, 7)
while True:
lights.green.on()
print("GREEN")
sleep(12)
lights.green.off()
lights.amber.on()
print("AMBER")
sleep(4)
lights.red.on()
lights.amber.off()
print("RED")
sleep(12)
lights.amber.on()
print("RED & AMBER")
sleep(4)
lights.red.off()
lights.amber.off()
比我尝试添加一个按钮,一个人行横道。但在这里我有问题。
下面的代码:
from gpiozero import Button, TrafficLights
from time import sleep
button = Button(21)
lights = TrafficLights(25, 8, 7)
def pedestrian_crossing():
sleep(4)
lights.off()
lights.amber.on()
print("Pedestrian crossing: AMBER")
sleep(4)
lights.red.on()
lights.amber.off()
print("Pedestrian crossing: RED")
sleep(12)
lights.amber.on()
print("Pedestrian crossing: RED & AMBER")
sleep(4)
lights.red.off()
lights.amber.off()
button.when_pressed = pedestrian_crossing
while True:
lights.green.on()
print("GREEN")
sleep(12)
lights.green.off()
lights.amber.on()
print("AMBER")
sleep(4)
lights.red.on()
lights.amber.off()
print("RED")
sleep(12)
lights.amber.on()
print("RED & AMBER")
sleep(4)
lights.red.off()
lights.amber.off()
我试图与button.wait_for_press
,button.wait_for_release
&有限,但button.is_pressed
是给我的最好成绩之一。
问题是,当我按下按钮时,函数被调用,但循环继续。那么我怎样才能重写代码,而不是当我按下循环停止的按钮时,函数被调用,函数内的所有内容都已完成,然后又回到循环?
还有另一种解决方案,与其他按钮属性?
在此先感谢!
谢谢您的回答@Skycc但更改'pedestrian_cross( )'在循环内部的绿灯后立即触发按下按钮。 –
我的错误,我检查函数名称,而不是var名称,修复它,请再试一次 – Skycc
Hi @Skycc!现在如预期的那样。我按下脚本运行的按钮,直到“if”和人行横道过程开始。但是当按下按钮开始行人过路处时,是否有办法立即中断循环?正如你在按下按钮时记住我的原始代码那样。唯一的问题是循环不停止。 ;-) 不管怎么说,还是要谢谢你!!! –