Lab 11: Buttons

In this lab, you will explore event-based programming through screen click events.


Tasks

L0. The setup

Create a Lab11 folder on your computer where you store CS151 projects and labs, hopefully somewhere that is backed up (e.g. in Dropbox, Google Drive, Microsoft One Drive, etc.)

Open up a Terminal and change the directory (cd) to the Lab11 folder.

Create the Nested Button Class

Download a copy of the Abstract Class Game and put it in your project directory.

Inside the provided Game class, define a nested class called Button. This inner class will allow any game inheriting from Game to easily create and manage clickable UI buttons.

L1a. Create the Button constructor

Create a constructor with the following parameters:

  1. self
  2. turt: a turtle.Turtle object used to draw the button
  3. topLeftX (int), topLeftY (int): coordinates of the button's top-left corner
  4. bottomRightX (int), bottomRightY (int): coordinates of the button's bottom-right corner
  5. buttonText (str): the label displayed inside the button
  6. borderColor (default "Black")
  7. fill (boolean)
  8. fillColor (default "White")
  9. fontColor (default "Blue")
  10. fontSize (int, default 12)

Inside the constructor:

  1. Store the passed-in arguments as instance variables (turt, topLeftX, topLeftY, bottomRightX, bottomRightY, text, fill, fontColor, and borderColor).
  2. Create an instance variable font assigned to a tuple ('Arial', fontSize, 'normal').
  3. Call self.draw() at the end of the constructor so the button automatically renders upon creation.

L1b. Create a draw method

Create a draw method inside Button that uses self.turt to render the button box and label:

L1c. Test drawing your button

At the bottom of GameABC.py, outside of the class, add a main function to test your button implementation:

Run GameABC.py. Your button should appear correctly.


L2. Make your button interactive

L2a. Create a pointInside method

Create a pointInside(self, pointX, pointY) method inside Button.

L2b. Test your button's interactivity

Inside your main function after defining quitButton and before calling mainloop.

Run GameABC.py. Your button should appear and clicking inside it should print "Quit clicked" to the terminal and close the window.


L3. Record a video of your interface

In your screen recording demo your button working.

I suggest using the screen recording feature of Quicktime on macOS or Xbox Game Bar on Windows 10.


Submit Lab Code and Video on Google Classroom

Upload and submit GameABC.py and your screen recording on Google Classroom.

Get started with the project

Once you are done with each of the lab tasks, you may start on the project checkin.


© 2021 Hannen Wolfe and Oliver Layton