Reputation: 2664
I have a wxPython application with some code like below. I want to set a value of an attribute of the class MyFrame, but I can't reference to it.
How can I make this code work?
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?
Upvotes: 1
Views: 158
Reputation: 92569
I think its somewhat poor designer for a child UI element to have specific knowledge about its parent. Its a backwards design. Children should usually have some way of signaling or raising an event and letting the appropriate listener react. But, if this is really want you want to do, then you probably want to get the parent item and act on it directly...
Note: Don't do this approach. I'm illustrating why the design has issues...
First off, you can't even do it with the way the code is structured, because other_class
has no reference to a parent. Its a generic instance. So you would have to do something like...
class other_class(object):
def __init__(self, parent):
self.parent = parent
And in your Notebook 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()
Then once your other_class now knows about its parent, you have to get the parent of the parent to have the MyFrame1 instance...
class other_class(object):
def __init__(self, parent):
self.parent = parent
def do_sth(self, value):
self.parent.GetParent().gauge_1.SetValue(value)
Do you see now why its a bad design? Multiple levels of objects have to assume knowledge of the parent structure.
I'm not up on my wxPython so I can't give you specifics, but here are some possible general approaches to consider:
other_class
really is. If its really meant to operate on children of your MyFrame1, then that functionality belongs under MyFrame1 so it can have knowledge of those members.other_class
were a wx object, it could emit a wx.Event when the do_sth()
method is called. You could bind that event at the MyFrame1 or Notebook level and do whatever work is needed in the handler.Upvotes: 1
Reputation: 7358
Try something like this:
class other_class(object):
def __init__(self):
self.g1=MyFrame1()
def do_sth(self):
self.g1.gauge_1.SetValue(value)
Upvotes: 0