how to pass globals across modules (wxPython)

Larry Bates lbates at syscononline.com
Mon Dec 20 10:20:23 EST 2004


I also struggled with this until I looked into many
of the wxWindows examples.  They all tend to pass in
the parent to each subsequent layer of classes so that
they can easily refer backwards in the hierarchy.

Example

In your code you will find that inside of SetTopWindow
you have parent as the first argument.  You can refer
to parent.someattribute or parent.somemethod to refer
back to "application", which is instance of MainApp.
Just do something similar in MainFrame class.

Changing MainFrame class a little and passing in
self as the first argument will give you the same
ability inside of MainFrame instance. Something like:

class MainFrame(wxFrame):
     def __init__(self, parentclass, parentframe):
	self.parentclass=parentclass
         wxFrame.__init__(self, parentframe, -1, "Frame Description")
         .
         .
         .

Then in Main App pass self as first argument (parentclass),
then you can refer back to MainApp instance as
self.parentclass.  If you go several levels down you
get self.parentclass.parentclass.parentclass.attribute:

class MainApp(wxApp):
     def OnInit(self):
         self.mainFrame = MainFrame(self, None)
         self.mainFrame.Show()
         self.SetTopWindow(self.mainFrame)
         return True

This might not be the "best" way, but seems to work and models
what wxWindows appears to do internally.

Larry Bates
Syscon, Inc.



Martin Drautzburg wrote:
> My wxPython program starts execution in mainFrame.py like this
>         [...]
>         class MainApp(wxApp):
>                 def OnInit(self):
>                         self.mainFrame = MainFrame(None)
>                         self.mainFrame.Show()
>                         self.SetTopWindow(self.mainFrame)
>                         return True
> 
> 
>         def main():
>                 global application
>                 application=MainApp(0)
>                 application.MainLoop()
> 
> 
>         if __name__ == '__main__':
>                 main()
> 
> 
> I need to access the "application" object from other modules, actually
> the windows and frames that live therein and I don't know how to do
> this.
> 
> I tried using "global", but that does not seem to help. In the other
> module I run an "import mainFrame" and that seems to reset the global
> variables.
> 
> Am I missing something obvious?



More information about the Python-list mailing list