Python Inheritence Help

I have a simple button class to make buttons
[code]
from graphics import *

class Button:

"""A button is a labeled rectangle in a window.
It is activated or deactivated with the activate()
and deactivate() methods. The clicked(p) method
returns true if the button is active and p is inside it."""

def __init__(self, win, center, width, height, label):
""" Creates a rectangular button, eg:
qb = Button(myWin, Point(30,25), 20, 10, 'Quit') """

w,h = width/2.0, height/2.0
x,y = center.getX(), center.getY()
self.xmax, self.xmin = x+w, x-w
self.ymax, self.ymin = y+h, y-h
p1 = Point(self.xmin, self.ymin)
p2 = Point(self.xmax, self.ymax)
self.rect = Rectangle(p1,p2)
self.rect.setFill('lightgray')
self.rect.draw(win)
self.label = Text(center, label)
self.label.draw(win)
self.deactivate()

def clicked(self, p):
"Returns true if button active and p is inside"
return self.active and
self.xmin <= p.getX() <= self.xmax and
self.ymin <= p.getY() <= self.ymax

def getLabel(self):
"Returns the label string of this button."
return self.label.getText()

def activate(self):
"Sets this button to 'active'."
self.label.setFill('black')
self.rect.setWidth(2)
self.active = True

def deactivate(self):
"Sets this button to 'inactive'."
self.label.setFill('darkgrey')
self.rect.setWidth(1)
self.active = False
[/code]
and I wanted to make a CustomButton class which inherited Button, except with a black button and green text, I tried this
[code]
class CustomButton(Button):
def __init__(self, win, center, width, height, label):
self.rect.setFill('black')
self.label.setFill('green')
[/code]
But I get this error:

Traceback (most recent call last):
File "calc.pyw", line 104, in <module>
theCalc = Calculator()
File "calc.pyw", line 21, in __init__
self.__createButtons()
File "calc.pyw", line 37, in __createButtons
self.buttons.append(CustomButton(self.win,Point(cx,cy),.75,.75,label))
File "calc.pyw", line 11, in __init__
self.rect.setFill('black')
AttributeError: CustomButton instance has no attribute 'rect'

Do I need to rewrite the entire __init__ to change this?

Comments

  • actually came up with this:

    [code]class CustomButton(Button):
    def changeColors(self,label,bg,outline):
    self.label.setFill(label)
    self.rect.setFill(bg)
    self.rect.setOutline(outline)[/code]

    and then just change it after making the button objects
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion