在主线程中获取在子线程中创建的对象

时间:2010-08-26 11:42:09

标签: python wxpython

假设我想要创建500个wxWidget(一些面板,颜色按钮和文本ctrl等),我必须一次创建所有这些,但这将冻结我的主线程,所以我把这个创建部分放在子线程中在主线程中显示一些gif动画。但我无法获得所有这些在子线程中在我的框架上创建的wxWidget对象。

我可以在主线程中获取wxWidgets(在子线程中创建)。  只是考虑一个案例,我必须在子线程和主线程显示动画中创建一个框架的子项。一旦子线程完成,子线程中创建的所有子线程应在主线程中可用。

任何帮助都非常明显。

我在windowsxp上使用python 2.5,wxpython 2.8。

2 个答案:

答案 0 :(得分:2)

您可以使用wxpython附带的pubsub - wx.lib.pubsub

有关线程间通信的基本使用示例,请参阅my answer here


替代方案:您可以使用wx.Yield更新窗口的示例。

import wx

class GUI(wx.Frame):
    def __init__(self, parent, title=""):
        wx.Frame.__init__(self, parent=parent, title=title, size=(340,380))
        self.SetMinSize((140,180))

        self.creating_widgets = False

        self.panel = wx.Panel(id=wx.ID_ANY, parent=self)

        self.startButton = wx.Button(self.panel, wx.ID_ANY, 'Start')
        self.stopButton = wx.Button(self.panel, wx.ID_ANY, 'Stop')
        self.messageBox = wx.TextCtrl(self.panel, wx.ID_ANY, '', size=(75, 20))

        self.Bind(wx.EVT_BUTTON,  self.onStart, self.startButton)     
        self.Bind(wx.EVT_BUTTON,  self.onStop, self.stopButton)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.startButton, 0, wx.ALL, 10)
        self.sizer.Add(self.stopButton, 0, wx.ALL, 10)
        self.sizer.Add(self.messageBox, 0, wx.ALL, 10)

        self.panel.SetSizerAndFit(self.sizer)

    def onStart(self, event):
        self.creating_widgets = True
        count = 0
        self.startButton.Disable()
        while self.creating_widgets:
            count += 1
            #Create your widgets here

            #just for simulations sake...
            wx.MilliSleep(100)
            self.messageBox.SetLabel(str(count))

            #Allow the window to update, 
            #You must call wx.yield() frequently to update your window
            wx.Yield()

    def onStop(self, message):
        self.startButton.Enable()
        self.creating_widgets = False


if __name__ == "__main__":

    app = wx.PySimpleApp()
    frame = GUI(None)
    frame.Show()
    app.MainLoop()

答案 1 :(得分:0)

您可以通过队列发回它们,或者这一切都发生在一个类的一个实例中,将小部件分配给实例中的某个已知位置以供主线程拾取它们。通过信号量发出信号。

相关问题