OO design, Python, and GUIs

Alan Gauld alan.gauld at btinternet.com
Tue Nov 18 18:41:11 EST 2003


On Tue, 18 Nov 2003 05:16:32 GMT, Christopher Culver
<christopher_culver_ForiguCxiTion at yahoo.com> wrote:
> of such a program. There should be, I gather, a core class "MainClass",
> which coordinates everything, other specialised classes which report to
> MainClass, and the GUI should ideally be in its own class "GuiClass".

That's one solution, it could also be a set of classes - one per
window or "form".

> Now GuiClass at the moment doesn't know anything about MainClass. When the
> program is started, an instance "mainClass" is created, which in turn
> creates an instance "guiClass". But how can guiClass report anything to
> the mainClass? 

If when you create the guiClass you pass a refernce to mainClass
into the constructor the gui can send messages back to it:

class mainClass:
   def __init__(self):
      ...
      self.gui = guiClass(self)
      ...

class guiClass:
   def __init__(self, application):
      self.application = application
      ...
   def someCommand(self):  # called by a widget somewhere
      self.application.someMethod(self.widgetValue)
      ...

So when the widgets call someCommand it sends the gui
data(widgetValue) back to the mainClass instance which it stores
in its self.application member.

You need to define the protocol between the two classes.
There are some fancier variations on this to improve reuse of
Gui elements, do a search on Model View Controller or MVC on
Google for other ideas.

> I imagine that I have to initalise the GuiClass instance in such a way
> that it knows about mainClass enough to be able to call its methods, but
> I've been unable find out how mainClass could pass itself to the GuiClass
> __init__.

The self value in the mainClass methods is a reference to the
mainClass instance. Just pass self to the GUI init.

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Python-list mailing list