Gianla
Gianla

Reputation: 63

Start Tk.mainloop() thread with another thread

I want to exec some code while Tk.mainloop() is running, so I think I need threading module.

I tried to put Tk.mainloop() inside the run method of a thread class and then I put the code I want to run while mainloop is running inside another thread.

from threading import Thread
import tkinter as tk

class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run():
        # window is tk.Tk()
        window.mainloop()

class MyCode(Thread):
# my code

TkinterThread = MyThread()
TkinterThread.start()
OtherThread = MyCode()
OtherThread.start()

and tkinter report me an error

RuntimeError: Calling Tcl from different apartment

so I searched on internet and I understand that the mainloop can be runned only out from thread becouse work in only one of them. So, is there a way to run others thread while mainloop is running?

Upvotes: 0

Views: 1122

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

You can run code in other threads. The problem isn't so much multiple threads per se, but that you've got tkinter code in more than one thread. All tkinter code needs to be in a single thread.

Usually it's best to make that your main thread (both creating the widgets and starting mainloop), and run your other code in a secondary thread or process. You can use a thread-safe queue to send information between the threads, such as when passing results back to the GUI.

Upvotes: 1

Related Questions