Chandan
Chandan

Reputation: 759

Tkinter and multi-threading

I was using the following code to examine if Tkinter works along with multithreading. But the following code doesn't work (the Gui becomes unresponsive as soon as it runs). Can anyone please explain why it doesn't work?

from threading import Thread 
import tkinter as tk

window = tk.Tk()
label = tk.Label(window, text='Hello')
label.pack()

def func():
    i = 1
    while True:
        label['text'] = str(i)
        i += 1

Thread(target=func).start()
Thread(target=window.mainloop).start()

Upvotes: 2

Views: 7703

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386342

It doesn't work because Tkinter doesn't support multithreading. Everything that interacts with a Tkinter widget needs to run in the main thread. If you want to use multithreading, put the GUI in the main thread and your other code in a worker thread, and communicate between them with a thread safe queue.

Upvotes: 3

Related Questions