簡體   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