0

I am trying to execute a function called alarm in background while function called clock is running. this is my alarm function. As code inside is complex I am only putting an example.

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

clock()
Alarm()
root.mainloop()

The Function isn't executing in background but it executes first and then GUI is started.

2 Answers 2

2

You can use after() to replace the while loop:

def alarm():
    current_time = dt.datetime.now().time()
    if current_time >= timetable[0]:
        print("It's time")
    else:
        # check again 1 second later
        root.after(1000, alarm)

clock()
alarm()
root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

1

You need threading:

import threading

# Your Alarm definition

alarm_thread = threading.Thread(target=Alarm)
main_thread = threading.Thread(target=root.mainloop)

alarm_thread.start()
main_thread.start()

The functions will now run concurrently, but be aware that it will be tricky to manage interactions between the two. I don't know how the clock function is defined or how you want it to run, but you can easily modify the code to make that one run concurrently too.

4 Comments

Thanks for info. Clock function is simple digital clock function using time module and a bit modification on GUI
Running mainloop() in a child thread may cause problem.
@acw1668 huh, I wasn't aware of that... how so?
tkinter don't recommend you call some tcl/tk command on another thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.