0

My tkinter application has a function which has a time.sleep() function in it so anytime I run the function that has the time.sleep() function, the whole application freezes until seconds specified in the time.sleep() function has elapsed. This can be a very bad User experience and I need to fix this.

The function that has the time.sleep() function is a call back function from a button so I tried doing something like this:

from tkinter import *
import threading
root = Tk()

schedule_msg_btn = Button(root, text="Schedule Msg", command=lambda : threading.Thread(target=schedule_msg_func).start())
root.mainloop()

It seems to be doing absolutely nothing.

Coder
  • 1
  • 3
  • 3
    The fix is not to use threading but to use `after()` method. There are hundreds of post about `sleep` and `after` in tkinter. For the most part any one of them can fix your problem. – Mike - SMT Feb 01 '23 at 13:25
  • Piggybacking on @Mike-SMT - [here's a link](https://www.pythontutorial.net/tkinter/tkinter-after/) to some documentation on the `after` method – JRiggles Feb 01 '23 at 13:27
  • Here is a post where I give an an example with after and funny enough an example with threading. https://stackoverflow.com/questions/58376456/python-tkinter-sleep-after-not-working-as-expected/58377804#58377804 – Mike - SMT Feb 01 '23 at 13:28
  • Okay, thanks alot. But what about a situation where the function runs a a for loop and the application still freezes how do I fix that – Coder Feb 01 '23 at 13:28
  • @Coder that sounds like a really heavy for loop. Depending on the implementation you can use threading to manage something that heavy but I would avoid threading if I were you as tkinter is not thread safe and as a beginner its best to avoid threading all together until you can fully understand what its doing and the correct way to use it. – Mike - SMT Feb 01 '23 at 13:29
  • Does this answer your question? [Python Tkinter sleep/after not working as expected](https://stackoverflow.com/questions/58376456/python-tkinter-sleep-after-not-working-as-expected) – Mike - SMT Feb 01 '23 at 13:30
  • Okay I've looked through the contents of the link and I must say they look promising ... Thanks for your help I'll try using after for the call back function and threading for the for loop .. – Coder Feb 01 '23 at 13:35
  • 1
    @Mike-SMT wow it worked... I mean the after widget ... Thanks – Coder Feb 01 '23 at 13:45
  • @coder the `after()` method was specifically designed to manage the timing issues to avoid the pitfalls of `sleep()` in a single threaded application like tkinters mainloop. Glad you got it working :) – Mike - SMT Feb 01 '23 at 13:48
  • @Mike-SMT thanks a lot. I was able to integrate the threading concept into most functions of my app and I have noticed that it is a lot smoother. And it sure will improve user experience. I just wonder how I have never really used threading in my other apps.... hehe – Coder Feb 03 '23 at 01:02

0 Answers0