2

我有一个按钮,可以创建一个新的子框架或显示已经创建的子框架。当我尝试单独使用 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.

4

1 回答 1

2

您可以使用 isinstance 检查它是否仍然存在。有关更多信息,请参阅此线程:https ://groups.google.com/forum/?fromgroups#!topic/wxpython-users/lMAylDnC7vM

或者你可以试试:

if self.logWin:
    self.logWin.Show()

http://wxpython-users.1045709.n5.nabble.com/is-there-a-method-to-test-if-an-wx-object-exists-td2356531.html

于 2012-07-16T20:46:17.290 回答