我有一个 wxPython 应用程序,其中包含如下代码。我想设置 MyFrame 类的属性值,但无法引用它。
我怎样才能让这段代码工作?
class MyFrame1(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.gauge_1 = wx.Gauge(self, -1)
self.notebook_1=myNotebook(self, -1)
class myNotebook(wx.Notebook):
def __init__(self, *args, **kwds):
wx.Notebook.__init__(self, *args, **kwds)
self.other_class_1=other_class()
self.other_class_1.do_sth()
class other_class(object):
def do_sth(self):
gauge_1.SetValue(value) #doesn't work of course, how do I do this?
最佳答案
我认为子 UI 元素的设计者如果对其父元素有具体的了解,这有点糟糕。这是一种向后的设计。 children 通常应该有某种方式发出信号或引发事件并让适当的听众使用react。但是,如果这确实是您想要做的,那么您可能想要获取父项并直接对其进行操作...
注意:不要采用这种方法。我正在说明为什么设计有问题......
首先,您甚至无法按照代码的结构方式执行此操作,因为 other_class
没有对父级的引用。它是一个通用实例。所以你必须做类似的事情......
class other_class(object):
def __init__(self, parent):
self.parent = parent
在你的笔记本类(class)中...
class myNotebook(wx.Notebook):
def __init__(self, *args, **kwds):
wx.Notebook.__init__(self, *args, **kwds)
# note here we pass a reference to the myNotebook instance
self.other_class_1 = other_class(self)
self.other_class_1.do_sth()
一旦你的 other_class 现在知道了它的父类,你就必须让父类的父类拥有 MyFrame1 实例...
class other_class(object):
def __init__(self, parent):
self.parent = parent
def do_sth(self, value):
self.parent.GetParent().gauge_1.SetValue(value)
你现在明白为什么这是一个糟糕的设计了吗?多个级别的对象必须假定了解父结构。
我不熟悉 wxPython,所以我无法向您提供具体信息,但这里有一些可以考虑的通用方法:
- 确定
other_class
的真正作用是什么。如果它确实要对 MyFrame1 的子级进行操作,那么该功能属于 MyFrame1,因此它可以了解这些成员。 - 如果
other_class
是一个wx对象,它可以在调用do_sth()
方法时发出一个wx.Event。您可以在 MyFrame1 或 Notebook 级别绑定(bind)该事件,并在处理程序中执行所需的任何工作。
关于python - 父引用问题 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642012/