gpt4 book ai didi

python - 如何将变量传递给主机?

转载 作者:太空宇宙 更新时间:2023-11-04 04:08:07 25 4
gpt4 key购买 nike

我可以将变量从主框架传递到第二框架,但是我不能成功,反之亦然吗?

错误:

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() 创建框架,但没有简单的方法从框架引用框架 B A.

只需修改创建框架 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))

关于python - 如何将变量传递给主机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56866920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com