while not error-如何做出替代

while not error-how to make an alternative

这是当前代码:

def wait_for_button(button):
    while not (button.read()) :
        pass
wait_for_button(push_button1)
print('Hi')
wait_for_button(push_button2)
print('Bye')

但是这段代码的问题是必须先按下 push_button1,只有这样,按钮 2 才会起作用。如果在按下按钮 2 之前没有按下按钮 1,则不会打印出 'Bye'(参考上面的代码)。

有没有一种方法可以不是按顺序 (pushputton1->pushbutton2) 而是按任何一种方式,即无论先按下哪个按钮,代码仍然有效? 谢谢

如果我没理解错的话,你想在按下按钮2时退出(不管按钮1是否被按下)。您可以为这种情况创建以下函数:

def wait_for_buttons(button1, button2):
    button1_pressed = False
    button2_pressed = False

    while not button2_pressed:
        if button1.read():
            button1_pressed = True
            print("Hi")
        if button2.read():
            button2_pressed = True

wait_for_buttons(push_button1, push_button2)
print('Bye')

如果我理解正确,你想检查是否按下了两个按钮,然后才打印 'Bye'。您可以为按钮 1 和 2 创建 2 个布尔变量,然后如果两个变量都设置为 true,则打印。 像这样:

def wait_for_button(button1,button2):
    button_pressed1=False
    button_pressed2=False

    print ("Hi")
    while not button_pressed1 and not button_pressed2:
        if button1.read():
            button_pressed1=True
        if button2.read():
            button_pressed2=True
    print ("Bye")

这样,先按下哪个按钮都没有关系,一旦按任何顺序按下两个按钮,while 循环结束,函数打印“Bye”。