【问题标题】:Exiting from a thread causes unresponsive GUI退出线程导致 GUI 无响应
【发布时间】:2015-01-10 01:52:55
【问题描述】:

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

我能够找到一种创建 wxPython 对话窗口的方法,以确定我的 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!"

【问题讨论】:

    标签: python multithreading user-interface wxpython


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多