I have a button that either creates a new child frame or shows the one that was already created. I ran into a problem when I tried to use Show() alone — if the user had exited the child frame, I would get an error because I was accessing a frame that no longer existed. I am currently using try/except to get around this, but is there a better way? Perhaps a Raise()-like function that handles this, or a way to check if the frame exists?
code:
#!/usr/bin/env python
import wx
class LogWindow(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.logger = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)
def Print(self):
self.Raise()
self.logger.AppendText("Hello, world\n")
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
panel=wx.Panel(self)
label = wx.StaticText(panel, -1, "Log this message:", pos=(10,10))
goButton = wx.Button(panel, label="Log", pos=(10,50))
self.Bind(wx.EVT_BUTTON, self.OnClick, goButton)
self.logWin = LogWindow(self)
#++++++++++++++++++++++++++
def OnClick(self, event):
try:
self.logWin.Show()
except:
self.logWin = LogWindow(self)
self.logWin.Show()
self.logWin.Print()
#++++++++++++++++++++++++++
class MyApp(wx.App):
def OnInit(self):
frame = MainWindow(None, -1, "MyApp")
frame.Show(True)
self.SetTopWindow(frame)
return True
#************************************************
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
The error I receive with self.logWin.Show() without the try/except is
wx._core.PyDeadObjectError: The C++ part of the LogWindow object has been deleted, attribute access no longer allowed.
You could use isinstance to check if it’s still there. See this thread for more info: https://groups.google.com/forum/?fromgroups#!topic/wxpython-users/lMAylDnC7vM
Or you could just try:
http://wxpython-users.1045709.n5.nabble.com/is-there-a-method-to-test-if-an-wx-object-exists-td2356531.html