【问题标题】:Debugging Tkinter code gives "RuntimeError: main thread is not in main loop"调试 Tkinter 代码给出“RuntimeError:主线程不在主循环中”
【发布时间】:2022-06-16 19:48:57
【问题描述】:

我知道互联网上充斥着关于 Tkinter 引发“RuntimeError:主线程不在主循环中”的问题。但几乎所有人都在讨论如何并行运行线程。 我没有(至少我猜是这样)。 我的问题是:代码完全可以独立运行。但是,一旦 GUI 在调试模式下显示出来,只需几秒钟的时间,就会发生此运行时错误。我最好的猜测:调试器本身在并行线程中运行?!? 如果我是对的:我能做些什么呢?如何可靠地调试使用 TKinter 的代码?

版本:

  • Visual Studio 代码 1.68
  • Python 3.9.13

小例子:

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()

应@MingJie-MSFT 的要求,这里是 Vscode 的 launch.json:

{
    // 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}
        }
    ]
}

...和错误报告:

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

【问题讨论】:

  • 它对我有用。我没觉得有什么不对。
  • 它也适用于我。你能提供你的launch.json和错误报告吗?
  • 感谢测试!好吧,这就是这个错误的障碍——有时它工作得很好,有时我每次调试代码时都会遇到这个错误。上面会添加launch.json和错误报告...

标签: python tkinter visual-studio-code


猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 2019-03-21
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多