2

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()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Chandan
  • 749
  • 1
  • 8
  • 11

1 Answers1

3

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • @Chandan: no. Frankly, I've rarely ever needed multithreading with a GUI app, and when I do I usually prefer multiprocessing over mulththreading. Are you _certain_ you need multiple threads, or are you simply assuming you do? You can do a lot of work in all of the spare cycles when the GUI isn't doing anything but waiting for events. – Bryan Oakley Feb 24 '13 at 22:24
  • Here is what I need to do: Suppose, clicking a button starts a process and then when I click another button, the process stops(I used 'pause' command in subprocess to do this) and then clicking another button kills that child process. So the previous event starts again. – Chandan Feb 24 '13 at 22:27
  • @Chandan: you definitely don't need multiple threads for that since you're already spawning another process. – Bryan Oakley Feb 24 '13 at 22:28
  • Can you please explain the difference between multithreading and multirocessing or give some reference? I don't know much about them. – Chandan Feb 24 '13 at 22:30
  • @Chandan: if you don't know what threads are, you absolutely shouldn't be writing code that uses them. They add a lot of complexity and can cause very subtle bugs unless you're careful. Here's a SO question specifically related to the differences between threads and processes: http://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread – Bryan Oakley Feb 24 '13 at 22:31
  • Ok. I think now I understand the difference. But how to run multiple processes in python without using multiple threads? – Chandan Feb 24 '13 at 22:37
  • @Chandan: comments aren't for extended discussions. If you have specific questions, ask them as questions on this site. – Bryan Oakley Feb 24 '13 at 22:43