在Python中从线程外部调用函数

时间:2016-05-05 08:46:55

标签: python multithreading python-3.x tkinter

我在调用顶层窗口的破坏功能时遇到问题,该顶层窗口位于Python 3中的一个线程中。它不会破坏窗口并且似乎在循环或其他东西中停滞。这是我的课程代码:

userErrorList

以下是我创建线程的方法:

class clientUI(Thread):
    sSock = None
    mID = 0
    yID = 0

    def __init__(self, sendSock, myID, yourID, q, looptime = 1.0/60):
        self.q = q
        self.timeout = looptime
        self.sSock = sendSock
        self.mID = myID
        self.yID = yourID
        self.first_click = True;
        super(clientUI, self).__init__()

    def onThread(self, function, *args, **kwargs):
        self.q.put((function, args, kwargs))

    def run(self):
        while True:
            try:
                function, args, kwargs = self.q.get(timeout=self.timeout)
                function(*args, **kwargs)
            except queue.Empty:
                self.idle()

    def idle(self):
        self.initDisplay()
        self.ui_input.insert(tkinter.END, "<Enter message>")
        self.ui_top.mainloop()

    def _eventDeleteDisplay(self):
        self.ui_top.pack_forget()
        self.ui_top.destroy()
    def eventDeleteDisplay(self):
        self.onThread(self._eventDeleteDisplay)

我希望能够从主线程调用eventDeleteDisplay()函数来破坏窗口,并且当我调用它时能够终止线程,但是没有一个发生。一切顺利,但窗口仍在那里,线程不会终止。以下是我从主线程中调用函数的方法:

def open_chat(sendSock, myID, yourID):
    q = queue.Queue()
    ui = clientUI(sendSock, myID, yourID, q, 1.0/60)
    try:
        ui.start()
    except KeyboardInterrupt:
        print("Caught CTRL-C, shutting down client")
        ui.eventDeleteDisplay()
    return ui

0 个答案:

没有答案