我可以将变量从主机传递到第二帧,但是我不能成功,反之亦然?
错误:
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
一样,我也将其放在了Main Frame中。不幸的是,它没有用。如何通过按按钮2 将变量从第二帧传递到主帧?
任何建议将不胜感激。谢谢。
答案 0 :(得分:1)
问题是您没有保存指向框架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))