退出线程会导致GUI无响应

时间:2014-11-13 01:55:54

标签: python multithreading user-interface wxpython

这是我之前提问的后续问题wxPython popup from calling imported function

我能够找到一种方法来创建一个wxPython对话框窗口,以确定我的GUI调用的线程是否应继续执行。我所做的只是在线程本身创建对话框窗口。但是,一旦我通过点击" no"在这个弹出窗口中,我的GUI中的关闭按钮变得没有响应,我无法关闭GUI本身。再一次,非常感谢您的帮助!

GUI代码:

import sys
import os
import re
import subprocess
import threading
import wx
import errno, os, stat, shutil
import extern_func

#this object redirects the external function output to the text box
class RedirectText(object):
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

#GUI code here
class progFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="functionGUI", size=(800, 600), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
        panel = wx.Panel(self)

        #more things....

        self.closeButton = wx.Button(panel, wx.ID_OK, "Run", pos=(250, 300))
        self.runButton = wx.Button(panel, wx.ID_OK, "Run", pos=(200, 300))

        self.out=wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.VSCROLL|wx.TE_READONLY, pos = (300, 50), size=(500, 200))

        #Run button event
        self.Bind(wx.EVT_BUTTON, self.OnRun, self.runButton)

        #close button event
        self.Bind(wx.EVT_BUTTON, self.OnClose, self.closeButton)

        #command prompt output to frame
        redir=RedirectText(self.out)
        sys.stdout=redir
        self.Show()

    def OnRun(self, event):
        t=threading.Thread(target=self.__run)
        t.start()

    def OnClose(self, event):
        self.Destroy()

    #external function call
    def __run(self):
        externFunc()

if __name__ == '__main__':
app = wx.App(False)
progFrame(None)
app.MainLoop()

外部功能代码:

import sys

def externFunc():
    print "Starting execution..."
    #a bunch of code...

    #this is the code for the Yes/No prompt and what introduced the buggy behavior
    if(os.path.isdir(mirror_source_path) or os.path.isdir(mirror_dest_path)):
        app = wx.App(False)
        dlg = wx.MessageDialog(None, "Something bad happened. Continue?","Warning",wx.YES_NO | wx.ICON_QUESTION)
        retCode = dlg.ShowModal()
        if (retCode == wx.ID_YES):
            print "Continuing."
        else:
            print "Aborted."
            return None
            sys.exit(0)
        dlg.Destroy()


    #more function code...
    print "Success!"

1 个答案:

答案 0 :(得分:0)

您不能同时运行2个wxPython主循环。这将导致一些非常棘手的行为。我个人认为我会将此代码拆分为2个线程。当第一个完成时,它使用wx.CallAfter和pubsub或wx.PostEvent发送消息,那时你可以在wxPython处理程序中执行if语句。

如果继续,则使用其余的功能代码启动第二个线程。