| 1 | |
| 2 | import wx |
| 3 | |
| 4 | |
| 5 | # This class is just an experiment to see how easy it would be to |
| 6 | # handle simulating transfer of ownership of object to a 'parent' |
| 7 | # object, and then automatically calling Destroy on those when the |
| 8 | # parent is destroyed. Conclusion: It's not too hard at all. Now, |
| 9 | # what should I do with it... |
| 10 | class DestroyWrapper(object): |
| 11 | def __init__(self): |
| 12 | import weakref |
| 13 | self.items = weakref.WeakValueDictionary() |
| 14 | |
| 15 | def AddItem(self, obj): |
| 16 | self.items[len(self.items)+1] = obj |
| 17 | |
| 18 | def __del__(self): |
| 19 | for item in self.items.values(): |
| 20 | item.Destroy() |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | class MyEvtHandler(wx.EvtHandler): |
| 27 | instCount = 0 |
| 28 | |
| 29 | def __init__(self): |
| 30 | wx.EvtHandler.__init__(self) |
| 31 | MyEvtHandler.instCount += 1 |
| 32 | self.cnt = MyEvtHandler.instCount |
| 33 | self.Bind(wx.EVT_CHECKBOX, self.OnCheckBox) |
| 34 | |
| 35 | def __del__(self): |
| 36 | print "%02d: deleted" % self.cnt |
| 37 | |
| 38 | def OnCheckBox(self, evt): |
| 39 | print "%02d: %s" % (self.cnt, evt.IsChecked()) |
| 40 | evt.Skip() |
| 41 | |
| 42 | |
| 43 | |
| 44 | class MyFrame(wx.Frame): |
| 45 | def __init__(self): |
| 46 | wx.Frame.__init__(self, None, title="wx.EvtHandler Test") |
| 47 | p = wx.Panel(self) |
| 48 | |
| 49 | pushBtn = wx.Button(p, -1, "Push EvtHandler", (20,20)) |
| 50 | popBtn = wx.Button(p, -1, "Pop EvtHandler", (20,60)) |
| 51 | |
| 52 | checkBox = wx.CheckBox(p, -1, "Test EvtHandler", (200, 25)) |
| 53 | |
| 54 | self.Bind(wx.EVT_BUTTON, self.OnPushBtn, pushBtn) |
| 55 | self.Bind(wx.EVT_BUTTON, self.OnPopBtn, popBtn) |
| 56 | |
| 57 | ## self.dw = DestroyWrapper() |
| 58 | |
| 59 | |
| 60 | def OnPushBtn(self, evt): |
| 61 | eh = MyEvtHandler() |
| 62 | self.PushEventHandler(eh) |
| 63 | ## self.dw.AddItem(eh) |
| 64 | print "%02d: pushed" % eh.cnt |
| 65 | |
| 66 | |
| 67 | def OnPopBtn(self, evt): |
| 68 | eh = self.GetEventHandler() |
| 69 | if eh.this == self.this: |
| 70 | print "All already popped!" |
| 71 | else: |
| 72 | eh = self.PopEventHandler() |
| 73 | print "%02d: popped( %s )" % (eh.cnt, eh.__class__) |
| 74 | eh.Destroy() |
| 75 | |
| 76 | |
| 77 | |
| 78 | app = wx.App(False) |
| 79 | frm = MyFrame() |
| 80 | frm.Show() |
| 81 | app.MainLoop() |