CSC111 clickMe3.py

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 15:06, 24 March 2010 (UTC)


# clickMe0.py
# A demo program that draws a button on the graphics window
# and waits for the user to click the mouse 10 times, counting
# and displaying the count at every tick. 
from graphics import *

def drawButton( win, x1, y1, w, h, label ):
    """draws a rectangle with the top-left corner at x1, y1,
    with width w and height h on the screen.  Puts the label
    in the middle of the rectangle"""
    r = Rectangle( Point( x1, y1 ),
                   Point( x1+w, y1+h ) )
    r.draw( win )
    r.setFill( "red" )
    t = Text( Point( x1 + w / 2, y1 + h / 2 ), label )
    t.draw( win )

def isInside( userPoint, x, y, w, h ):
    mx = userPoint.getX()
    my = userPoint.getY()
    if x <= mx <= x+w and y <= my <= y+h:
        return True
    else:
        return False

def main():
    """Opens a graphics window 300x300 and draws a button on
    it.  Then wait for the user to click the mouse 10 times
    before exiting"""
    W = 300
    H = 300
    win = GraphWin( "Click Me!", W, H )
    border = 10

    #--- draw the button ---
    L = [ [ border, border, 70, 20, "Button1" ],
          [ W-border-70, border,70, 20, "Button 2" ],
          [ W-border-70, H-border-20, 70, 20, "Button 3" ] ]

    for x, y, w, h, label in L:
        drawButton( win, x, y, w, h, label )

    #--- draw "click me!" in middle of screen ---
    t = Text( Point( W/2, H/2 ), "click me!" )
    t.draw( win )

    #--- get 10 mouse clicks and count them ---
    for i in range( 1000 ):
        userPoint = win.getMouse()
        count = 0
        for x, y, w, h, label in L:
            if isInside( userPoint, x, y, w, h ):
                count += 1
        if count!=0:
            t.setText( "Inside #" + str(i+1) )
        else:
            t.setText( "Outside #" + str(i+1) )

        
    #--- wait for  one more click and close up window---
    #win.getMouse()
    win.close()

main()