簡體   English   中英

(Python tkinter):RuntimeError:主線程不在主循環中

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

我用 tkinter 編寫了一個 python GUI 程序,它顯示一個 label,根據變量“loadings”中列表的時間順序,它的文本每 0.25 秒更改一次。 我通過將 function 作為線程使其工作。 否則,它不會起作用。 該代碼按預期完美運行。 但是,每次我關閉程序時,都會出現 RuntimeError,我不知道是什么問題。 我在 inte.net 上搜索了錯誤,但我發現的所有內容都與 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

原因是您在 Tkinter 循環中使用了線程,我想我們不應該這樣做。 安全播放是使用after 所以自定義 label 可以在這種情況下幫助我們

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

暫無
暫無

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

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