简体   繁体   中英

(Python tkinter): RuntimeError: main thread is not in main loop

I coded a python GUI program with tkinter that displays a label wherein its text changes every 0.25 seconds, according to the chronology of the list in the variable 'loadings'. I made it work by putting the function as a thread. Otherwise, it would not work. The code works perfectly as intended. However, every time i close the program, a RuntimeError appears and i do not know what the problem is. I searched on the inte.net for the error but none of what i have found are related to tkinter at all.

code:

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

error:

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

The reason is that u have used the Threading in the Tkinter loop which I guess we shouldn't. Safe play is to use after . so Custom label can help us in this case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM