前些日子我看見StackOverflow的一個問題,說如何動態地延時創建以及銷毀容器。我那時就回答說他可以參考我以前寫過的有關於如何動態創建與銷毀按鈕的技術博客,但也許對方實在太懶而根本沒有考慮那個建議。
所以這篇文章中,我演示給大家一個范例,看看如何動態延時創建一個容器並接著銷毀的過程。
以下就是需要的代碼:import wx ######################################################################## class PanelOne(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) self.countdown = wx.StaticText(self, label="This panel will self-destruct in 10 seconds") ######################################################################## class PanelTwo(wx.Panel): """""" #---------------------------------------------------------------------- def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) txt = wx.StaticText(self, label="Panel Two") ######################################################################## class MainFrame(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="Panel Smacker") self.panelOne = PanelOne(self) self.time2die = 10 self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.update, self.timer) self.timer.Start(1000) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.panelOne, 1, wx.EXPAND) self.SetSizer(self.sizer) #---------------------------------------------------------------------- def update(self, event): """""" if self.time2die < 0: self.panelOne.Destroy() self.panelTwo = PanelTwo(self) self.sizer.Add(self.panelTwo, 1, wx.EXPAND) self.Layout() self.timer.Stop() else: msg = "This panel will self-destruct in %s seconds" % self.time2die self.panelOne.countdown.SetLabel(msg) self.time2die -= 1 if __name__ == "__main__": app = wx.App(False) frame = MainFrame() frame.Show() app.MainLoop()當你直接運行時,你會第一次看到下圖這樣:
然後大概10秒後,你才會看到如下圖這樣: