Python:在时间归零后中断timer.repeat()(在树莓派上)

问题描述 投票:0回答:1

我正在使用 guizero 编写 python 脚本。有一个按钮,它的命令运行一个函数。这个函数是在我在 youtube 上找到的 PomodoraTimer Tutorial 之后构建的。到目前为止,它有效,但我希望它在警报运行后停止。代码如下:

#UserInterface, GPIO-Steuerung und Timer-Steuerung importieren
from guizero import App, Text, TextBox, PushButton, Box, Window
import RPi.GPIO as GPIO
import time
import datetime

#this is what gets triggered by the Pushbutton
def startTimer():
    global timer
    if (set_time_input.value == "" and set_time_input_min.value == ""):
        currentTimeLeft = "3" #60 #set timer to 1 minuit if textfield empty
    else:
        if (set_time_input.value != ""  and set_time_input_min.value == ""):
            currentTimeLeft = int(set_time_input.value)
        else:
            currentTimeLeft = int(set_time_input_min.value) * 60

    #Countdownanzeige
    timer = Text(timer_box, text="\r"+str(currentTimeLeft), size=30, color="red")
    timerbottom = Text(timer_box, text="\n Sekunden.")
    timer.repeat(1000, reduceTime)

def reduceTime():
    global timer
    if int(timer.value) > 0:
        timer.value = int(timer.value) -1
    else:
        start_alarm_1() #this triggers a GPIO on my Raspi for 3 seconds
        #exit()

#####this is just the rest of the app if ou want to build it and test it:

#GPIO Steuerung initialisieren
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()

#Start Alarm -> i've got a remote alarm that works this way ;)
def start_alarm_1():
    GPIO.setup(20, GPIO.OUT)
    GPIO.output(20, GPIO.LOW)
    time.sleep(3)
    GPIO.output(20, GPIO.HIGH)
#App-Fenster initialisieren
app = App(title="OSCE Timer", width=800, height=400)
#textfields to set timer time
textfield_msg = Text(app, text="Timer in seconds:")
set_time_input = TextBox(app)
textfield_msg = Text(app, text="OR timer in Minutes:")
set_time_input_min = TextBox(app)
run_timer_button = PushButton(app, command=startTimer, text="start Countdown")
#timer window in app
timerTitle = Text(app, text="Time:\n")
#Appwindow
app.display()

我的问题是:如果在reduceTime()中timer.value变为“0”,那么闹钟就会一遍又一遍地开始。这是因为timer.repeat()函数一遍又一遍地触发reduceTime()函数——永远。现在我有多个想法:围绕repeat()函数构建一个while循环,将return -1语句添加到不同的地方,但都不起作用。如果有人能帮助我,我会很高兴! (while 语句的问题:它不再显示我的计时器,因为该函数卡在 while 循环 obv 中。)

python timer raspberry-pi gpio
1个回答
0
投票

该死,经过几个小时的尝试,我发布了这个 - 几秒钟后我找到了解决方案!

我必须添加以下行来插入我也使用过的“#exit()”语句:

time.cancel(reduceTime)
© www.soinside.com 2019 - 2024. All rights reserved.