[Tutor] You're gridded for life. [OOP using __getattr__]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Dec 2001 14:20:31 -0800 (PST)

On Tue, 11 Dec 2001, Jean Montambeault wrote:

> tom_dee_lee_dum = Entry(fen).grid(row=0, column=0)

Yes, I remember now.  As you've discovered, the non-buggy version of
this is:

> tom_dee_lee_dum=Entry(fen)
> tom_dee_lee_dum.grid(row=0, column=0)
> tom_dee_lee_dum.bind("<Return>", here_I_am)

But what you wrote before, this "bug", seems to be a common one that
beginning Tkinter programmers do a lot!  Perhaps it might be nice to
actually allow some kind of shortcut like this.

We can write a "ShortcutEntry" class of Entry widgets with slightly
different behavior.  Here's an example that might be useful for you:

import Tkinter

class ShortcutEntry:
    """This is a small class that demonstrates how to customize an
    Entry widget without subclassing."""
    def __init__(self, *args, **kwargs):
        self.entry = Tkinter.Entry(*args, **kwargs)

    def pack(self, *args, **kwargs):
        self.entry.pack(*args, **kwargs)
        return self.entry

    def grid(self, *args, **kwargs):
        self.entry.grid(*args, **kwargs)
        return self.entry

    def __getattr__(self, name):
        """We delegate pretty much everything to our underlying
        return getattr(self.entry, name)

This class should allow us to do:

tom_dee_lee_dum = ShortcutEntry(fen).grid(row=0, column=0)

with the effect that we're looking for.

As a personal opinion, I think that the Tkinter widgets should do
something like this anyway, to make Tkinter programming more convenient.  
However, I get the feeling that the above code might upset a few people.  
*grin*  What do other people think about this?

> in no tutorial is "extreme tolerance to frustration" ever mentioned
> among the qualities that make a good programmer but it really should.

When things start getting too frustrating, start spilling the problem to
Tutor.  Let's help each other avoid frustration.

Best of wishes to you.