我有一个按钮,可以创建一个新的子框架或显示已创建的子框架。当我尝试单独使用Show()时遇到问题 - 如果用户退出了子框架,我会收到一个错误,因为我正在访问一个不再存在的框架。我目前正在使用try / except来解决这个问题,但有更好的方法吗?也许是一个类似Raise()的函数来处理这个,或者检查框架是否存在的方法?
代码:
#!/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()
我在 self.logWin.Show()
没有使用try / except时收到的错误是
wx._core.PyDeadObjectError: The C++ part of the LogWindow object has been deleted, attribute access no longer allowed.
答案 0 :(得分:2)
您可以使用isinstance检查它是否仍然存在。有关详细信息,请参阅此主题:https://groups.google.com/forum/?fromgroups#!topic/wxpython-users/lMAylDnC7vM
或者你可以试试:
if self.logWin:
self.logWin.Show()