简体   繁体   English

按键时如何停止闹钟?

[英]How to stop the alarm when key pressed?

I'm trying to write a python code for alarm clock. 我正在尝试为闹钟编写python代码。 I've 2 doubts - 我有2个疑问-
1) Comparison between local time and user input time doesn't occur unless i add a 0 before every single digit number. 1)除非我在每个数字前添加0,否则不会发生本地时间与用户输入时间之间的比较。 Ex- h:m:s = 08:09:35. 例如-h:m:s = 08:09:35。 It's not working if i type - 8:9:35 如果我键入-8:9:35这是行不通的
2)How can i stop an alarm when any key is pressed? 2)当按下任意键时如何停止闹钟? "input" command isn't working. “输入”命令不起作用。

code: 码:

#strfime is of type string
#localtime is of time int

#using strftime
import time
from pygame import mixer

def sound():
    mixer.init()
    mixer.music.load("F:\learn\python\music1.mp3")  #file is 28 seconds long

def userinput():

    print("current time is: ",time.strftime("%H:%M:%S"))  
    h=(input("Enter the hour: "))               
    m=(input("Enter the minutes: "))
    s=(input("Enter the seconds: "))
    alarm(h,m,s)


def alarm(h,m,s):  
    n=2                         #rings twice in 1 minute.

    while True: 
        if time.strftime("%H") == h and time.strftime("%M") == m and time.strftime("%S") == s:

            print("wake up!!!! \n")
            break

    sound()
    while n>0:                                  #code for ringing twice in a minute.
        mixer.music.play()
        time.sleep(30)                          #alarm should stop when any key pressed.
        mixer.music.stop()
        n-=1


    snooze_in = input("Do you want to snooze? press y or n. ")

    if snooze_in == 'y':
        print("The alarm will start in 5 seconds")
        time.sleep(5)               #snooze for x seconds
        h=time.strftime("%H")
        m=time.strftime("%M")
        s=time.strftime("%S")

        return alarm(h,m,s)

    else:
        exit()    



if __name__=="__main__":
    userinput()

You could use datetime objects and then subtract the start from the end datetime to get a timedelta object. 您可以使用datetime对象,然后从结束datetime中减去开始时间,以获得一个timedelta对象。 Afterwards use the total_seconds of the timedelta to calculate the end time in milliseconds (by adding it to pygame.time.get_ticks() ) and play the alarm sound when the alarm time - pygame.time.get_ticks() is less than 0. 然后使用timedelta的total_seconds计算结束时间(以毫秒为单位)(通过将其添加到pygame.time.get_ticks() ),并在警报时间-pygame.time.get_ticks()小于0时播放警报声音。

To stop the timer you could put the timer code into an if clause ( if timer_active: ) and set timer_active = False when the user presses a key ( S in the example below). 要停止计时器,您可以将计时器代码放入if子句中( if timer_active:并在用户按下键时设置timer_active = False (在下面的示例中为S )。

import datetime
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
SOUND = pg.mixer.Sound(r"C:\Dokumente\Pythonprogramme\win3.wav")


def main():
    start = datetime.datetime.now()
    print("current time is: ", start)
    h = int(input("Enter the hour: "))
    m = int(input("Enter the minutes: "))
    s = int(input("Enter the seconds: "))
    # I just pass the current year, month and day here, so it'll
    # work only if the end time is on the same day.
    end = datetime.datetime(start.year, start.month, start.day, h, m, s)
    timedelta = end-start
    alarm_time = pg.time.get_ticks() + timedelta.total_seconds()*1000
    repeat_time = 3000  # Repeat the alarm after 3000 ms.
    timer_active = True

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_s:
                    # Stop the sound and the timer.
                    SOUND.stop()
                    timer_active = False

        if timer_active:
            if alarm_time - pg.time.get_ticks() < 0:  # Time is up.
                SOUND.play()  # Play the sound.
                # Restart the timer by adding the repeat time to the current time.
                alarm_time = pg.time.get_ticks() + repeat_time

        screen.fill(BG_COLOR)
        pg.display.flip()
        clock.tick(60)


if __name__ == '__main__':
    main()
    pg.quit()

Note that this example works only if the end time is on the same day. 请注意,此示例仅在结束时间是同一天时才有效。

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

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