首页 > 解决方案 > (Python tkinter):RuntimeError:主线程不在主循环中

问题描述

我用 tkinter 编写了一个 python GUI 程序,它显示一个标签,其中它的文本每 0.25 秒更改一次,根据变量“加载”中列表的年表。我通过将函数作为线程使其工作。否则,它将无法正常工作。该代码按预期完美运行。但是,每次我关闭程序时,都会出现 RuntimeError,我不知道问题是什么。我在互联网上搜索了错误,但我发现的所有内容都与 tkinter 无关。

代码:

from tkinter import *
import threading, time
root = Tk()
loading_label = Label(root)
loading_label.pack()
loadings = ['loading', 'loading.', 'loading..', 'loading...']
def loadingscreen():
    while True:
        for loading in loadings:
            loading_label.config(text=loading)
            time.sleep(0.25)
loadingthread = threading.Thread(target=loadingscreen)
loadingthread.start()
root.mainloop()

错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/HP/PycharmProjects/myfirstproject/threadingtest.py", line 14, in loadingscreen
    loading_label.config(text=loading)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1637, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1627, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
RuntimeError: main thread is not in main loop

Process finished with exit code 0

标签: pythonmultithreadingtkinter

解决方案


原因是你在 Tkinter 循环中使用了线程,我想我们不应该这样做。安全发挥就是使用after。所以自定义标签可以在这种情况下帮助我们

from tkinter import *
import threading, time
import sys
root = Tk()
class Custom(Label):
    def __init__(self,parent,lst):
        super().__init__(parent)
        self['text']=lst[0]
        self.marker=0
        self.lst=lst[:]
        self.note=len(lst)
        self.after(250,self.change)
    def change(self):
        if self.marker>=self.note:self.marker=0
        self['text']=self.lst[self.marker]
        self.marker+=1
        self.after(250,self.change)
loadings = ['loading', 'loading.', 'loading..', 'loading...']
loading_label = Custom(root,loadings)
loading_label.pack()
# destroy it whenever u want
root.mainloop()

推荐阅读