[Python-Dev] PEP 343 - Abstract Block Redux

Shane Hathaway shane at hathawaymix.org
Mon May 16 04:11:02 CEST 2005


Ka-Ping Yee wrote:
> On Sun, 15 May 2005, Shane Hathaway wrote:
> 
>>You might add to the PEP the following example, which could really
>>improve the process of building GUIs in Python:
>>
>>    class MyFrame(Frame):
>>        def __init__(self):
>>            with Panel():
>>                with VerticalBoxSizer():
>>                    self.text = TextEntry()
>>                    self.ok = Button('Ok')
> 
> 
> I don't understand how this would be implemented.  Would a widget
> function like 'TextEntry' set the parent of the widget according to
> some global 'parent' variable?  If so, how would 'Panel' know that
> its parent is supposed to be the 'MyFrame' object?

Try this version, which I sent to Nick earlier:

    class MyFrame(Frame):
        def __init__(self):
            with Panel(self):
                with VerticalBoxSizer(self):
                    self.text = TextEntry(self)
                    self.ok = Button(self, 'Ok')

The 'self' parameter tells the component to add itself to the current
parent inside the Frame.  The current parent is a temporary variable set
by 'with' statements.  Outside any 'with' statement, the current parent
is the frame.

There is only a little magic.  Maybe someone can find an even less
magical pattern, but it's a lot easier to read and write than the status
quo:

    class MyFrame(Frame):
        def __init__(self):
            p = Panel()
            self.add(p)
            sizer = VerticalBoxSizer(p)
            p.add(sizer)
            self.text = TextEntry()
            sizer.add(self.text)
            self.ok = Button('Ok')
            sizer.add(self.ok)

Shane


More information about the Python-Dev mailing list