繁体   English   中英

如何调用回调然后 go 回到 Python 中的 while 循环

[英]How to invoke callback then go back to while loop in Python

我希望有人可以帮助我解决以下问题。 我有一个树莓派,在 linux 上有一个带有 GPIZero 的外部按钮。 我想要它,所以当我按下按钮时,python 会打印一次“按下按钮”,在我释放按钮之前不会打印任何其他内容。 释放按钮后,我希望 python 每三秒打印一次“循环”。 当我按下按钮时,我总是希望提前完成最新的loop() function。

所以基本上,在启动时,python 应该一遍又一遍地打印“循环”,直到我按下按钮。 当我按下按钮时, loop()过程应该在 python 打印“按下按钮”之前完成。 然后,只要我按住按钮,就不会打印任何其他内容。 当我释放按钮时,它应该 go 回到循环“循环”。

现在我下面的内容不起作用,但它非常接近完成我想要的。 问题是这段代码,我相信:

if button.is_pressed:
        if timer ==1:
            button.when_pressed = press

当我按下 timer=1 的按钮时,我必须再次按下按钮(非常非常快),以便它运行我所描述的 press() function。 我想按住按钮一次,让press() function 运行。 我知道它的设置是如何的。 我相信button.when_pressed没有注册按钮在到达代码中的那个点时已经被按下。 我必须再次快速按下按钮以获取 go 的代码。 当它没有嵌套在其他button.is_pressed部分时,我觉得它更喜欢它。 但是,我不知道该怎么做。 我觉得我两个都需要。 我想保留button.when_pressed回调,因为它只像我想要的那样打印“按钮被按下”一次,并一直保持到我释放按钮,但我无法使用 If -statements 让它自己工作。 同时,按住按钮时仅使用button.is_pressed会使 python 循环“按下按钮”打印,这是我不想要的。

任何帮助,将不胜感激。

#!/usr/bin/python3

from gpiozero import Button
from time import sleep

import time

button = Button(4)
timer = 0

def press():
    print("Button is pressed")

def loop():
    global timer
    timer =  0
    print('loop')
    sleep(3)
    timer = 1

#button.when_released = release

while True:

    if button.is_pressed:
        if timer ==1:
            button.when_pressed = press
            sleep(4)
            button.when_pressed = None

    else:
        loop()
def MainLoop():
    is_pressed = False
    while True:
        if not is_pressed and button.is_pressed:
           is_pressed = True
           do_something()
        else if is_pressed and not button.is_pressed:
           is_pressed = False

只需维护 state...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM