Reputation: 1
I created a tkinter alarm clock which is not responding after setting the alarm. The alarm sound is playing but after that I have to exit the application and re-run the code to set alarm once again .I have shared the code and screenshot of the app.
from tkinter import
import datetime
import time
from playsound import playsound
def Alarm(set_alarm_timer):
while True:
time.sleep(1)
actual_time = datetime.datetime.now()
cur_time = actual_time.strftime("%H:%M:%S")
cur_date = actual_time.strftime("%d/%m/%Y")
msg="Current Time: "+str(cur_time)
print(msg)
if cur_time == set_alarm_timer:
playsound("Audio.mp3")
break
def get_alarm_time():
alarm_set_time = f"{hour.get()}:{min.get()}:{sec.get()}"
Alarm(alarm_set_time)
window = Tk()
window.title("Alarm Clock")
window.geometry("400x160")
window.config(bg="#922B21")
window.resizable(width=False,height=False)
time_format=Label(window, text= "Remember to set time in 24 hour format!", fg="white",bg="#922B21",font=("Arial",15)).place(x=20,y=120)
addTime = Label(window,text = "Hour Min Sec",font=60,fg="white",bg="black").place(x = 210)
setYourAlarm = Label(window,text = "Set Time for Alarm: ",fg="white",bg="#922B21",relief = "solid",font=("Helevetica",15,"bold")).place(x=10, y=40)
hour = StringVar()
min = StringVar()
sec = StringVar()
hourTime= Entry(window,textvariable = hour,bg = "#48C9B0",width = 4,font=(20)).place(x=210,y=40)
minTime= Entry(window,textvariable = min,bg = "#48C9B0",width = 4,font=(20)).place(x=270,y=40)
secTime = Entry(window,textvariable = sec,bg = "#48C9B0",width = 4,font=(20)).place(x=330,y=40)
submit = Button(window,text = "Set Your Alarm",fg="Black",bg="#D4AC0D",width = 15,command = get_alarm_time,font=(20)).place(x =100,y=80)
window.mainloop()
Upvotes: 0
Views: 223
Reputation:
.mainloop
is some sort of while loop
. So time.sleep()
and while ...
will mess with it. Use .after()
.
Edit: .place()
,.pack()
and .grid()
geometry managers return None
. And in python, the value of the last function is assigned.
here, it would be None
, and might raise errors in future
def Alarm(set_alarm_timer):
actual_time = datetime.datetime.now()
cur_time = actual_time.strftime("%H:%M:%S")
if cur_time != set_alarm_timer:
msg="Current Time: "+str(cur_time)
print(msg)
window.after(1000,Alarm, set_alarm_timer)
else:
playsound("Audio.mp3")
...
submit = Button(window,text = "Set Your Alarm",fg="Black",bg="#D4AC0D",width = 15,command = lambda: Alarm(f"{hour.get()}:{min.get()}:{sec.get()}"),font=(20))
submit.place(x =100,y=80)
Upvotes: 1