SahilM
SahilM

Reputation: 128

I am trying to execute an alarm function in tkinter but it is not working properly

I am trying to Execute the function in tkinter as I want function to run in background I have done following code. Also I am trying to execute it inside a while loop but its not looping through.

t1 = dt.time(hour = 13, minute= 24)
t2 = dt.time(hour= 13, minute= 4)
timetable = [t1, t2]
root = Tk() 

def Alarm():
      current_time = now_time.strftime("%H:%M:%S")
      print(current_time)
      print(timetable[0])
      while True:
            if timetable[0] <= dt.datetime.now().time():
                print("Its time")
            break
Alarm()
root.mainloop()

print statements are only for testing. The logic I am using in alarm clock is also not executing properly as it tells ""Its time" even after time has passed. I have tried following methods before.

method 1:

for i in reversed(timetable):
    i_time = i
    #print (i_time)
    #print(now_time.strftime("%H:%M"))
    while True:
        if dt.datetime.now().time() < i_time:
        #if i_time <= dt.datetime.now().time():
            print("Its Time")
            break

method 2:

for i in timetable:
    current_time = dt.datetime.now().time()
    alarm_time = i
    while True:
        if current_time < alarm_time:
            if current_time <= alarm_time:
                print("its time", alarm_time)

Using for loop was my first goal but for loop isn't executing properly. It only gets 1st element and doesn't go to 2nd element even if first element has passed so I have decided to go with if,elif,else statement

Upvotes: 0

Views: 56

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385910

You can use the after method to run a function after a certain amount of time has elapsed. You should use it rather than creating a loop.

You simply need to convert the alarm time to a number of milliseconds, then use that to ring the alarm at the given time. For example, to ring an alarm in one hour you would do this:

def ring_alarm():
    print("Its time")
delay = 60 * 60 * 1000  # 60 min/hour, 60 secs/min, 1000ms/sec
root.after(delay, ring_alarm)

Upvotes: 1

SahilM
SahilM

Reputation: 128

I am going with if..else response for executing alarm as

current_time = dt.datetime.now().time()
        if timetable[0] == current_time:
              
              print("Its time")
              break

I was breaking While loop in wrong place as well an typo from my end.

Upvotes: 0

Related Questions