簡體   English   中英

調試 Tkinter 代碼給出“RuntimeError:主線程不在主循環中”

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

我知道互聯網上到處都是關於 Tkinter 提出“RuntimeError:主線程不在主循環中”的問題。 但幾乎所有人都在討論如何並行運行線程。 我沒有(至少我猜是這樣)。 我的問題是:代碼完全可以獨立運行。 但是,一旦 GUI 在調試模式下顯示出來,只需幾秒鍾的時間,就會發生此運行時錯誤。 我最好的猜測:調試器本身在並行線程中運行?!? 如果我是對的:我能做些什么呢? 如何可靠地調試使用 TKinter 的代碼?

版本:

  • 視覺工作室代碼 1.68
  • 蟒蛇 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

RuntimeError:主線程不在主循環中 Tcl_AsyncDelete:異步處理程序被錯誤的線程刪除

1.您可以將線程設置為守護進程:

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

2.Tkinter 實際上有一個線程安全的替代方案mtTkinter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM