CSC111 myRectangle2.py

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 13:07, 14 April 2010 (UTC)


# myRectangles.py
# D. Thiebaut
# Demonstration of inheritance with Python Classes
# In this program myRect inherits from Rectangle.
# Rectangle is the base class
# myRect is the derived class
# it adds a label in the center of the rectangle

from graphics import *


class myRect( Rectangle ):
    """Derived class for a rectangle with a label in it"""

    def __init__( self, P1, P2, label="Unknown" ):
        """Constructor for the class"""
        #--- initializes the base class ---
        Rectangle.__init__( self, P1, P2 )

        #--- puts the lable in the middle ---
        x1 = P1.getX()
        y1 = P1.getY()
        x2 = P2.getX()
        y2 = P2.getY()
        self.label = Text( Point( (x1+x2)/2, (y1+y2)/2 ), label )

    def draw( self, win ):
        #--- draw the rectangle and the label ---
        Rectangle.draw( self, win )
        self.label.draw( win )


def waitForClick( win, message ):
    """ waitForClick: stops the GUI and displays a message.  
    Returns when the user clicks the window. The message is erased."""
 
    # wait for user to click mouse to start
    startMsg = Text( Point( win.getWidth()/2, win.getHeight()/2 ), message )
    startMsg.draw( win )    # display message
    win.getMouse()          # wait
    startMsg.undraw()       # erase
 
def main():
    """displays the graphics window and an instance of myRect"""
    win = GraphWin( "Inheritance", 400, 400 )
    r = myRect( Point( 20,20 ), Point( 150, 50 ), "Hello there!" )
    r.draw( win )
    waitForClick( win, "Click to quit" )

main()