[pygtk] Ok. A new try...

Gonzalo Aguilar Delgado gad at aguilardelgado.com
Fri Mar 24 19:20:21 WST 2006


Hi Tim!

It's better avoid recursion if you have too much deep levels.
Will try this also...

Thank you for your help.
This will be keept here and will help a lot of people also.

I'm new to python (only 've done few things in blender) but loveling
it....



Avoid recursion

> John Ehresman wrote:
> > Gonzalo Aguilar Delgado wrote:
> >> How do I find a widget (say a GtkEntry) inside it with the name
> >> "txtbox"?
> > 
> > You need to go through all the children and find the one with the name. 
> >   Try the following:
> > 
> > def all_descendants(w, flags=None):
> >   """ Generator to traverse all descendants of a widget in depth-first 
> >   order.  Assumes that the widget hierarchy doesn't change during the 
> >   traversal.  Use flags to only return widgets where widget & flags is
> >   true.  If a widget is filtered out, all of its descendants are also
> >   filtered out. """
> > 
> >   if not isinstance(w, gtk.Container):
> >     return
> > 
> >   for child in w.get_children():
> >     if flags is None or child.flags() & flags:
> >       yield child
> > 
> >       for g_kid in all_descendants(child):
> >         yield g_kid
> > 
> > def find_named(parent, name):
> >   for w in all_descendants(parent):
> >     if w.get_name() = name:
> >       return w
> >   return None
> > 
> > entry = find_named(frame, 'txtbox')
> > 
> > You probably do want to make sure that only one widget with the name 
> > 'txtbox' is a descendant of frame.  gtk does not enforce this for you.
> 
> I generally prefer to avoid the recursion and use something like this:
> 
>      def all_descendants(root):
>          stack = [root]
>          while stack:
>              w = stack.pop()
>              yield w
>              if isinstance(w, gtk.Container):
>                  stack.extend(reversed(w.get_children()))
>              if isinstance(w, gtk.MenuItem):
>                  submenu = w.get_submenu()
>                  if submenu:
>                      stack.append(submenu)
> 
> Submenus don't count as children but for most things it's useful to have
> them listed in the same way.  I would also recommend putting all the
> widgets into a dictionary if you'll be doing these lookups often:
> 
>      def named_widgets(root):
>           r = {}
>           for w in all_descendants(root):
>               name = w.get_name()
>               if name:
>                   r[name] = w
>           return r
> 
-- 
Gonzalo Aguilar Delgado - Ingeniero en Informática
        [ Seguridad & Medios de pago ]



More information about the pygtk mailing list