monoceros84
monoceros84

Reputation: 118

Debugging Tkinter code gives "RuntimeError: main thread is not in main loop"

I know the internet is full of questions about Tkinter raising "RuntimeError: main thread is not in main loop". But almost all of them discuss about how to run threads in parallel. I don't (at least I guess that). My problem is: the code runs completely fine stand-alone. But as soon as a GUI is shown in debugging mode it's only a question of seconds until this Runtime Error occurs. My best guess: the debugger itself runs in a parallel thread?!? If I am right: what can I do about it? How can I reliably debug code that uses TKinter?

Versions:

Minimal example:

import tkinter as tk
import tkinter.ttk as ttk


class GUI(ttk.Frame):
    def __init__(self, master):
        # Initialize.
        super().__init__(master)
        self.grid(row=0, column=0, sticky=tk.N + tk.E + tk.S + tk.W)
        # Create radio buttons
        self.button = ttk.Radiobutton(self, text='Yes', value=True)
        self.button.grid(row=0, column=0, sticky=tk.E)
        self.button2 = ttk.Radiobutton(self, text='No', value=False)
        self.button2.grid(row=0, column=1, sticky=tk.E)
        # Put an OK button to the bottom right corner.
        self.w_ok = ttk.Button(self, text='OK', command=self._exit)
        self.w_ok.grid(row=100, column=2, sticky=tk.SE)
    def _exit(self):
        self.master.destroy()


if __name__ == '__main__':
    root = tk.Tk()
    gui = GUI(root)
    gui.mainloop()

On request of @MingJie-MSFT here is the launch.json of Vscode:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Aktuelle Datei",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "autoReload": {"enable": true}
        }
    ]
}

... and the error report:

Exception ignored in: <function Variable.__del__ at 0x000001B5B67451F0>
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 363, in __del__
    if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread

Upvotes: 2

Views: 1337

Answers (1)

MingJie-MSFT
MingJie-MSFT

Reputation: 9347

RuntimeError: main thread is not in main loop Tcl_AsyncDelete: async handler deleted by the wrong thread

1.You can set the thread to a Daemon:

t = threading.Thread(target=your_func)
t.setDaemon(True)
t.start()

2.There actually is a thread-safe alternative to Tkinter, mtTkinter.

Upvotes: 2

Related Questions