1

I wrote a gui class using Tkinter:

def start_gui():

    def do_some_task():
      dosometask

    def do_some_task2():
      dosometask2

    ttk.Button(mainframe, text="task1", command=do_some_task).grid(column=1, row=3, sticky=W)
    ttk.Button(mainframe, text="task2", command=do_some_task2).grid(column=2, row=3, sticky=W)


if __name__ == "__main__":
   start_gui()

When I press either one of the buttons the GUI is freezing until the task is finished. How can threading be used to prevent this, making both buttons usable at all times?

kabe
  • 11
  • 3
  • How long do they freeze for in terms of time? – 3141 Dec 31 '17 at 18:15
  • until the function finishing his job and return – kabe Dec 31 '17 at 18:15
  • How long is that for your computer in seconds? – 3141 Dec 31 '17 at 18:16
  • What exactly is `dosometask`? – Nae Dec 31 '17 at 18:16
  • 1
    it's doing some text searching in very long string – kabe Dec 31 '17 at 18:17
  • 1
    use module `threading` to run `dosometask` and then it will not block `mainloop()` and it will not freeze GUI. Or you can try to use periodically `root.update()` inside `dosometask` so it will force `mainloop` to execute one loop and it will refresh GUI. – furas Dec 31 '17 at 18:34
  • you mean like this: def do_some_task: threading.Thread(target=dosometask)).start() – kabe Dec 31 '17 at 18:36
  • yes. BTW: two days ago was question how to use [tkinter + thread + queue to update label in window](https://stackoverflow.com/a/48021054/1832058) – furas Dec 31 '17 at 18:57
  • simpler [example with tkinter+thread+queue](https://github.com/furas/python-examples/blob/master/tkinter/thread-queue/main%20.py) – furas Dec 31 '17 at 19:11
  • Sorry, but none of the answers is working for me. I'm keep getting freeze with the functions – kabe Dec 31 '17 at 20:38

1 Answers1

0

tkinter is single-threaded. While a function is running it is unable to service events, including events such as requests to redraw the window.

If your buttons call functions that take more than a couple hundred milliseconds or so, you'll need to run them in a separate thread or process in order for tkinter to be responsive.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685