繁体   English   中英

Tkinter多线程队列永远等待

[英]Tkinter multithreading queue waits forever

我的tkinter应用程序有2个线程(我需要它们),我在stackoverflow上发现了一个很棒的函数tkloop(),该函数是为tkinter-only-one-main-thread编写的。 它使用队列。 当我这样做时,它的确显示了tkMessagebox:

self.q.put((tkMessageBox.askyesno,("Cannot download it", "Download \"" + tag +"\" via internet site"),{}, self.q1 ))

但是当我创建自己的函数时,它不执行该函数

self.q.put((self.topleveldo,(resultlist),{},None))

只有一个类的应用程序:

self.q=Queue()
def tkloop(self):
    try:
        while True:
            f, a, k, qr = self.q.get_nowait()
            print f
            r = f(*a,**k)

            if qr: qr.put(r)
    except:
        pass
    self.okno.after(100, self.tkloop)
def topleveldo(resultlist):
    print ("executed - actually this never prints")
    self.choice=Toplevel()
    self.choices=Listbox(self.choice)
    for result in resultlist:
        self.choices.insert(END,str(result))
    choosebutton=Button(text="Vybrat",command=self.readchoice)
def readchoice(self):
    choice=int(self.choices.curselection())
    self.choice.destroy()
    self.q1.put(choice)

App类中的方法中的另一个代码,由第二个线程运行:

def method(self):
    self.q1=Queue()
    self.q.put((self.topleveldo,(resultlist),{},None))
    print ("it still prints this, but then it waits forever for q1.get, because self.topleveldo is never executed")
    choice=self.q1.get()

在tkloop异常处理程序中记录错误-现在您不知道对topleveldo的调用是否失败(可能是失败)。 问题在于(1) (resultlist)只是结果列表,而不是像topleveldo期望的那样带有1个参数的元组。 并且(2)tkloop仅在消息中的第4个参数是队列时才发出响应。 您可以使用以下方法修复它:

self.q.put((self.topleveldo,(resultlist,),{},self.q1))

添加:

即使tkloop捕获到异常,它也应始终返回一条消息,以便调用者可以可靠地调用q.get()以获得响应。 一种方法是返回被调用程序引发的异常:

def tkloop(self):
    while True:
        try:
            f, a, k, qr = self.q.get_nowait()
            print f
            r = f(*a,**k)
            if qr: 
                qr.put(r)
            del f,a,k,qr
    except Exception, e:
        if qr:
            try:
                qr.put(e)
            except:
                # log it
                pass
    self.okno.after(100, self.tkloop)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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