我可以将变量从“主机”传递到“第二帧”,但是不能成功,反之亦然?

错误:

Traceback (most recent call last):
  File "C:\Users\GCS-User\Desktop\with canvas\__or(class_variable).py", line 33, in OnButton2
    self.textCtrl1.SetValue(self.parent.z)
AttributeError: 'NoneType' object has no attribute 'z'


代码:

# -*- coding: utf-8 -*-

import wx

class A (wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.Frame.__init__(self, parent)
        bSizer1 = wx.BoxSizer( wx.VERTICAL )
        self.startButton1 = wx.Button( self, wx.ID_ANY, u"Button1", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer1.Add( self.startButton1, 1, wx.ALL|wx.EXPAND, 5 )
        self.startButton2 = wx.Button( self, wx.ID_ANY, u"Button2", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer1.Add( self.startButton2, 1, wx.ALL|wx.EXPAND, 5 )

        self.textCtrl1 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer1.Add( self.textCtrl1, 1, wx.ALL|wx.EXPAND, 5 )

        self.SetSizer( bSizer1 )
        self.Layout()

        self.startButton1.Bind(wx.EVT_BUTTON, self.OnButton1)
        self.startButton2.Bind(wx.EVT_BUTTON, self.OnButton2)
        self.count = 0


    def OnButton1(self, event):
        self.x = 5 + self.count
        self.y = 7 + self.count
        B(self).Show()
        self.count += 1

    def OnButton2(self, event):
        self.textCtrl1.SetValue(self.parent.z)

class B(wx.Frame):
    def __init__(self, parent):
        self.parent = parent
        wx.Frame.__init__(self, parent)
        bSizer1 = wx.BoxSizer( wx.HORIZONTAL )

        self.startButton3 = wx.Button( self, wx.ID_ANY, u"Button3", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer1.Add( self.startButton3, 1, wx.ALL|wx.EXPAND, 5 )

        self.textCtrl2 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer1.Add( self.textCtrl2, 1, wx.ALL|wx.EXPAND, 5 )

        self.SetSizer( bSizer1 )
        self.Layout()

        self.startButton3.Bind(wx.EVT_BUTTON, self.OnButton3)

        self.z = self.parent.x + self.parent.y

    def OnButton3(self, event):
        self.textCtrl2.SetValue(str(self.z))
        #self.parent.textCtrl1.SetValue(str(self.z))


app = wx.App()
frame = A(None)
frame.Show(True)
app.MainLoop()


就像第二帧具有self.parent = parent一样,我也将其放置在“主框架”中。不幸的是,它没有用。如何通过按按钮2将变量从第二帧传递到主帧?

任何建议,将不胜感激。谢谢。

最佳答案

问题是您没有保存指向帧B的指针。使用B(self).Show()创建帧,但是没有简单的方法从帧A引用帧B。

只需修改创建框架B的方式即可。请参见下面的class A修改方法。

def OnButton1(self, event):
    self.x = 5 + self.count
    self.y = 7 + self.count
    self.bFrame = B(self)
    self.bFrame.Show()
    self.count += 1

def OnButton2(self, event):
    self.textCtrl1.SetValue(str(self.bFrame.z))

10-07 13:29