我有一个 threading.Thread 的子类,我用它来创建 wx.Panels(因为它们中的大多数是 I/O 绑定的)并通过 wx.PostEvent 将它们发送到我的 wx.Frame。
问题是线程结束后,发送的面板被破坏并丢失,留下框架空白。我认为这与线程本身在执行后被销毁有关。将 time.sleep(s) 添加到线程的最后一行允许在 s 秒内看到框架内的面板,而线程被冻结,证明面板实际上是创建的。
以下是您可能感兴趣的框架代码:
self.Bind(MyEvents.EVT_CONTROL_NEWPANEL,self.ChangePanel)
def ChangePanel(self,event):
if self.panel != None:
self.panel.Hide()
self.panel = event.panel
self.panel.Show()
和 threading.thread 子类的一个:
class ThreadExecute(threading.Thread):
def __init__(self,func,args):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.start()
def run(self):
apply(self.func,self.args)
CreateRandomPanel(parent):
panel = RandomPanel(parent)
event = MyEvents.Control_NewPanel(panel = panel)
wx.PostEvent(parent,event)
线程结束后有没有办法让对象保持活动状态?对 Thread 上的对象进行酸洗并在框架上对其进行脱酸是一个不错的选择吗?
编辑:
一个小的可运行代码示例:
import wx
import threading
from wx.lib.newevent import NewEvent
from time import sleep
NewPanelEvent, EVT_NEWPANEL = NewEvent()
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,size=wx.Size(350,350))
self.panel = None
self.Bind(EVT_NEWPANEL,self.ChangePanel)
self.control = MyControl(self)
self.control.NewPanel()
def ChangePanel(self,event):
if self.panel != None:
self.panel.Hide()
self.panel = event.panel
#self.Refresh()
class MyPanel(wx.Panel):
def __init__(self,parent,size):
wx.Panel.__init__(self,parent,size=size)
self.btn = wx.Button(self,label='hit me!',pos=wx.Point(25,25),size=wx.Size(75,25))
self.SetBackgroundColour(wx.Colour(255,255,0))
class MyControl(object):
def __init__(self,window):
self.window = window
def NewPanel(self):
MyThread(RandomFunction,(self.window,))
class MyThread(threading.Thread):
def __init__(self,func,args):
threading.Thread.__init__(self)
self.func = func
self.args = args
self.start()
def run(self):
apply(self.func,self.args)
def RandomFunction(window):
sleep(3)
# size = window.GetSizeTuple()
size = (250,250)
panel = MyPanel(window,size=size)
event = NewPanelEvent(panel = panel)
wx.PostEvent(window,event)
# use the sleep to prevent the thread from ending, so you can see the panel
sleep(5)
class App(wx.App):
def OnInit(self):
self.frame = MyFrame()
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main():
app = App(False)
app.MainLoop()
if __name__ == '__main__':
main()