[Tkinter-discuss] Public properties in Tkinter superclasses?

Jeff Cagle jrcagle at juno.com
Fri Jan 26 03:33:26 CET 2007

Hi all,

  I wrote a small "can you match the color?" program.  The user is 
confronted with a 4-bit/chan. color code such as '#3F6' and must click 
the button out of six whose color matches the code.  Feedback in the 
form of 'that color is #8D2' is given.  There is also a Reset button so 
that the user can try a different panel of six colors when he desires.

Anyways, because I needed each button to display different feedback, I 
ended up inheriting from the Button base class.  The original intent was 
to create a color public property that could be set and gotten:

class MyButton(Button):

    HEX = "0123456789ABCDEF"
    def __init__(self, master):
        self.color = self.rand_color()
        Button.__init__(self, master, \
                        command = self.report)
       def get_color(self):
           return self['fg']
      def set_color(self, color):
           self['fg'] = color
      color = property(get_color, set_color)

    def rand_color(self):
        return '#' + ''.join([random.choice(self.HEX) for x in range(3)])
    def report(self):
        Answer.set("That color is %s" % self.color)

Oddly, though, the get_color and set_color methods did not work properly 
on Reset.  For the first run, the colors are set and gotten correctly.  
But if the reset code is called,

def restart(self):
        for x in self.buttons:
            x.color = x.rand_color()
        s = random.choice(self.buttons).color

the new colors are not set.  Further, if new colors are assigned 
manually, the call to get_color() returns the originally assigned 
color.  BUT, if I comment out the set_ and get_ methods and the 'color = 
property()' line, and allow color to be a normal private property, then 
this works to assign new colors:

def restart(self):
        for x in self.buttons:
            x.color = x.rand_color()
            x['fg'] = x.color
        s = random.choice(self.buttons).color

The only difference appears to be that I'm manually calling x['fg'] 
instead of relying on set_color() to do so for me.  I can't fathom why 
that would make a difference.

Do Tkinter classes not allow for property() s?


More information about the Tkinter-discuss mailing list