43

当我打电话

self.client = ThreadedClient() 

在我的 Python 程序中,我得到了错误

“RuntimeError:主线程不在主循环中”

我已经做了一些谷歌搜索,但不知何故我犯了一个错误......有人可以帮我吗?

完整错误:

Exception in thread Thread-1:
    Traceback (most recent call last):
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 530, in __bootstrap_inner
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 483, in run
    File "/Users/Wim/Bird Swarm/bird_swarm.py", line 156, in workerGuiThread
    self.root.after(200, self.workerGuiThread)
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 501, in after
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1098, in _register
    RuntimeError: main thread is not in main loop

课程:

class ThreadedClient(object):

    def __init__(self):
        self.queue = Queue.Queue( )
        self.gui = GuiPart(self.queue, self.endApplication)
        self.root = self.gui.getRoot()
        self.running = True
        self.GuiThread = threading.Thread(target=self.workerGuiThread) 
        self.GuiThread.start()

    def workerGuiThread(self):
        while self.running:
            self.root.after(200, self.workerGuiThread)
            self.gui.processIncoming( )     

    def endApplication(self): 
        self.running = False

    def tc_TekenVogel(self,vogel):
        self.queue.put(vogel)

class GuiPart(object):
    def __init__(self, queue, endCommand): 
        self.queue = queue
        self.root = Tkinter.Tk()
        Tkinter.Canvas(self.root,width=g_groottescherm,height=g_groottescherm).pack()
        Tkinter.Button(self.root, text="Move 1 tick", command=self.doSomething).pack()
        self.vogelcords = {} #register of bird and their corresponding coordinates 

    def getRoot(self):
        return self.root

    def doSomething():
        pass #button action

    def processIncoming(self):
        while self.queue.qsize( ):
            try:
                msg = self.queue.get(0)
                try:
                    vogel = msg
                    l = vogel.geeflocatie()
                    if self.vogelcords.has_key(vogel):
                        cirkel = self.vogelcords[vogel]
                        self.gcanvas.coords(cirkel,l.geefx()-g_groottevogel,l.geefy()-g_groottevogel,l.geefx()+g_groottevogel,l.geefy()+g_groottevogel)            
                    else:
                        cirkel = self.gcanvas.create_oval(l.geefx()-g_groottevogel,l.geefy()-g_groottevogel,l.geefx()+g_groottevogel,l.geefy()+g_groottevogel,fill='red',outline='black',width=1)
                        self.vogelcords[vogel] = cirkel 
                    self.gcanvas.update()
                except:
                    print('Failed, was van het type %' % type(msg))
            except Queue.Empty:
                pass
4

6 回答 6

52

您正在主线程之外的线程中运行主 GUI 循环。你不能做这个。

文档在一些地方随便提到 Tkinter 不是线程安全的,但据我所知,从来没有完全站出来说你只能从主线程与 Tk 交谈。原因是事实有些复杂。Tkinter 本身线程安全的,但很难以多线程方式使用。最接近官方文档的似乎是这个页面

问:是否有线程安全的 Tkinter 替代方案?

特金特?

只需在主线程中运行所有 UI 代码,然后让编写者写入 Queue 对象……</p>

(给出的示例代码不是很好,但足以弄清楚他们的建议并正确地做事。)

实际上一个 Tkinter 的线程安全替代方案mtTkinter。它的文档实际上很好地解释了这种情况:

尽管 Tkinter 在技术上是线程安全的(假设 Tk 是使用 --enable-threads 构建的),但实际上在多线程 Python 应用程序中使用时仍然存在问题。问题源于 _tkinter 模块在处理来自其他线程的调用时试图通过轮询技术获得对主线程的控制。

我相信这正是您所看到的:您在 Thread-1 中的 Tkinter 代码正试图窥视主线程以找到主循环,但它不存在。

所以,这里有一些选择:

  • 做 Tkinter 文档推荐的事情,并在主线程中使用 TkInter。可能通过将当前的主线程代码移动到工作线程中。
  • 如果您正在使用其他一些想要接管主线程的库(例如,twisted),它可能有一种与 Tkinter 集成的方法,在这种情况下您应该使用它。
  • 用来mkTkinter解决问题。

此外,虽然我没有找到这个问题的任何确切重复项,但有许多关于 SO 的相关问题。有关更多信息,请参阅此问题此答案以及更多信息。

于 2013-02-04T20:26:46.403 回答
17

我知道这已经很晚了,但是我将线程设置为守护进程,并且没有引发异常:

t = threading.Thread(target=your_func)
t.setDaemon(True)
t.start()
于 2019-12-01T21:59:51.323 回答
11

我找到了解决它的方法。它可能看起来像一个笑话,但你应该添加

plt.switch_backend('agg')
于 2020-10-31T12:59:33.360 回答
4

由于所有这些确实帮助了我的问题,但并没有完全解决它,这里还有一点需要记住:

就我而言,我开始在许多线程中导入 pyplot 库并在那里使用它。将所有库调用移至我的主线程后,我仍然收到该错误。

我确实通过在其他线程中使用的其他文件中删除该库的所有导入语句来摆脱它。即使他们没有使用该库,同样的错误也是由它引起的。

于 2018-12-30T23:24:57.707 回答
2
from tkinter import *
from threading import Thread
from time import sleep
from random import randint

class GUI():

    def __init__(self):
        self.root = Tk()
        self.root.geometry("200x200")

        self.btn = Button(self.root,text="lauch")
        self.btn.pack(expand=True)

        self.btn.config(command=self.action)

    def run(self):
        self.root.mainloop()

    def add(self,string,buffer):
        while  self.txt:
            msg = str(randint(1,100))+string+"\n"
            self.txt.insert(END,msg)
            sleep(0.5)

    def reset_lbl(self):
        self.txt = None
        self.second.destroy()

    def action(self):
        self.second = Toplevel()
        self.second.geometry("100x100")
        self.txt = Text(self.second)
        self.txt.pack(expand=True,fill="both")

        self.t = Thread(target=self.add,args=("new",None))
        self.t.setDaemon(True)
        self.t.start()

        self.second.protocol("WM_DELETE_WINDOW",self.reset_lbl)

a = GUI()
a.run()

也许这个例子会对某人有所帮助。

于 2020-04-28T20:40:10.587 回答
1

写在最后:

root.mainloop()

当然,如果不是,则代替root应该是您的对象的名称。Tkroot

于 2020-07-01T20:56:19.963 回答