[英]How to stop the alarm when key pressed?
我正在嘗試為鬧鍾編寫python代碼。 我有2個疑問-
1)除非我在每個數字前添加0,否則不會發生本地時間與用戶輸入時間之間的比較。 例如-h:m:s = 08:09:35。 如果我鍵入-8:9:35這是行不通的
2)當按下任意鍵時如何停止鬧鍾? “輸入”命令不起作用。
碼:
#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()
您可以使用datetime對象,然后從結束datetime中減去開始時間,以獲得一個timedelta對象。 然后使用timedelta的total_seconds
計算結束時間(以毫秒為單位)(通過將其添加到pygame.time.get_ticks()
),並在警報時間-pygame.time.get_ticks()小於0時播放警報聲音。
要停止計時器,您可以將計時器代碼放入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()
請注意,此示例僅在結束時間是同一天時才有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.