我开发了一个代码,可以让我设置一个可以播放音效的闹钟:
import time
import tkinter as tk
import playsound
window = tk.Tk()
window.title('Alarm clock')
#where the problem lies
def submit():
hr=int(txtHr.get('1.0',tk.END))
minute=int(txtMin.get('1.0',tk.END))
sec=int(txtSec.get('1.0',tk.END))
while True:
time2=time.localtime()
nowHr=time2.tm_hour
nowMin=time2.tm_min
nowSec=time2.tm_sec
if nowHr==hr:
if nowMin ==minute:
if nowSec==sec:
playsound.playsound('D:/Python/Project/Alarm.mp3')
break
window.columnconfigure([0,2],minsize=70)
lbHr=tk.Label(text='Hour',font='italic')
lbHr.grid(row=0,column=0)
lbMin=tk.Label(text='Min',font='italic')
lbMin.grid(row=0,column=1)
lbSec=tk.Label(text='Sec',font='italic')
lbSec.grid(row=0,column=2)
txtHr=tk.Text(fg='white',bg='blue',width='2',height='1')
txtHr.grid(row=1,column=0,pady=5)
txtMin=tk.Text(fg='white',bg='blue',width='2',height='1')
txtMin.grid(row=1,column=1)
txtSec=tk.Text(fg='white',bg='blue',width='2',height='1')
txtSec.grid(row=1,column=2)
lbHow=tk.Label(text='The clock first show you the current time, \nnow type in the time of the alarm.')
lbHow.grid(row=2,columnspan=3)
butStart=tk.Button(text='Set alarm clock',command=submit)
butStart.grid(row=3,columnspan=3,pady=5)
t=time.localtime()
txtHr.insert('1.0',str(t.tm_hour))
txtMin.insert('1.0',str(t.tm_min))
txtSec.insert('1.0',str(t.tm_sec))
window.mainloop()
当我设置闹钟并且窗口超过 5 秒时,它停止响应:
令人惊讶的是,它仍然有效,警报仍然响起。当然,没有响应的窗口并不理想,那么我该如何解决呢?我应该使用datetime
模块,甚至有什么区别吗?