尝试在另一个线程wxpython中创建对话框

Rip*_*de4 5 python multithreading wxwidgets wxpython dialog

我正在另一个线程中运行一个函数,该线程应该填写一个对话框然后显示它,但是只要我尝试以任何方式更改该对话框,它就会出现段错误。我已经读到这是WxPython的常见问题,并且开发人员无意直接更改另一个线程中的对话框。

我该如何解决?我可以在主线程中调用该函数,但这会阻塞我的GUI,并且初始化对话框是一项冗长的操作-我想避免这种情况。

我的代码类似于以下内容。

在主线程中

# Create the dialog and initialize it
thread.start_new_thread(self.init_dialog, (arg, arg, arg...))
Run Code Online (Sandbox Code Playgroud)

我正在调用的功能

def init_dialog(self, arg, arg, arg....):
  dialog = MyFrame(self, "Dialog")

  # Setup the dialog
  # ....
  dialog.Show()
Run Code Online (Sandbox Code Playgroud)

即使对话框为空,而只是在函数内部显示一个简单的调用,我仍会遇到分段错误。任何帮助将不胜感激,谢谢。

tho*_*r18 5

我制作了一个小程序来演示在计算过程中保持 GUI 响应并在计算后调用消息框。

    import wx
    import threading
    import time


    class TestFrame(wx.Frame):

        def __init__(self):
            wx.Frame.__init__(self, None, -1, "I am a test frame")
            self.clickbtn = wx.Button(self, label="click me!")
            self.Bind(wx.EVT_BUTTON, self.onClick)

        def onClick(self, event):
            self.clickbtn.Destroy()
            self.status = wx.TextCtrl(self)
            self.status.SetLabel("0")
            print "GUI will be responsive during simulated calculations..."
            thread = threading.Thread(target=self.runCalculation)
            thread.start()

        def runCalculation(self):
            print "you can type in the GUI box during calculations"
            for s in "1", "2", "3", "...":
                time.sleep(1)
                wx.CallAfter(self.status.AppendText, s)
            wx.CallAfter(self.allDone)

        def allDone(self):
            self.status.SetLabel("all done")
            dlg = wx.MessageDialog(self,
                                   "This message shown only after calculation!",
                                   "",
                                   wx.OK)
            result = dlg.ShowModal()
            dlg.Destroy()
            if result == wx.ID_OK:
                self.Destroy()

    mySandbox = wx.App()
    myFrame = TestFrame()
    myFrame.Show()
    mySandbox.MainLoop()
Run Code Online (Sandbox Code Playgroud)

GUI 内容保存在主线程中,而计算继续不受阻碍。根据您的需要,计算结果在创建对话框时可用。