# Stephanie Taylor and Bruce Maxwell # Spring 2015 # We added a new parameter to the GraphWin creation function. It expects # the type of input to be a pointer to a function that takes information about # an event as its input. This file demonstrates how to use it. # We also added getFill and getOutline methods to the graphics shapes. This makes # it possible to check the current color of a shape. # The updated graphics code is a new a new module named graphicsPlus. import graphicsPlus as gr # Make a "complex" shape that is really just one rectangle. But since it is a "complex shape", # it belongs in a list. def box_init( x, y, scale ): r = gr.Rectangle( gr.Point( x, y ), gr.Point( x+100*scale, y+100*scale ) ) r.setFill( "purple" ) return [r] # return the list containing just this rectangle # This function is called with a list of graphcis object whenever a key # is pressed. The event tells us which key was pressed. # This one changes the color of the first shape in the list (which also happens to be # the only one), depending on which key was pressed. def handleKeyPressedBox( boxshapes, event ): if event.keysym == "Left": print "Pressed the left arrow" if boxshapes[0].getFill() == "red": boxshapes[0].setFill( "orange" ) else: boxshapes[0].setFill( "red" ) elif event.keysym == "Right": print "Pressed the right arrow" if boxshapes[0].getFill() == "purple": boxshapes[0].setFill("slate grey") else: boxshapes[0].setFill( "purple" ) elif event.keysym == "Up": print "Pressed the up arrow" if boxshapes[0].getFill() == "green": boxshapes[0].setFill( "#113311" ) else: boxshapes[0].setFill( "green" ) elif event.keysym == "Down": print "Pressed the down arrow" if boxshapes[0].getFill() == "blue": boxshapes[0].setFill("black") else: boxshapes[0].setFill( "blue" ) def main(): # We need to define our complex shapes before creating the window if we want to # use the key-pressing code. box = box_init( 100, 100, 1 ) # Make a function whose input is just the event( That is what the GraphWin is # expecting). But we want our function to also take the list of shapes as input. # So I am writing a nested function that can use the shapes list stored in the box variable # This is a nested function and is useful in this situation, when I need some way # of getting the box list's value to handleKeyPressedBox. def handleKeyPressed( event ): handleKeyPressedBox( box, event ) # Now we can create the window as pass it the arrow to the handleKeyPressed function win = gr.GraphWin( "Press a Key", 300, 300, False, handleKeyPressed ) # Draw the box shapes in the newly created window for shape in box: shape.draw( win ) # Wait for the mouse. In the meantime, if you click on the top of the window # (to make it the main program being run), handleKeyPressed will execute, which will, # in turn, call handleKeyPressedBox. win.getMouse() win.close() if __name__ == '__main__': main()