What Are User Interfaces?
A User Interface (UI) allows users to interact with your program. Pygame is a Python library used to create interactive user interfaces and applications. It provides tools for creating windows, handling events (like mouse clicks and keyboard inputs), and drawing graphics.
Installing Pygame
1. Launch VSCode and open terminal
Mac: Go to Terminal > New Terminal from the top menu
Windows: Press “Ctrl+Shift+`” or go to View > New Terminal from the top menu.
2. Check if Python is installed: In the terminal, type the following command:
python3 --version
python3 -m ensurepip --upgrade
python3 -m pip install --upgrade pip
2. Confirm pip
is installed:
python3 -m pip install pygame
3. Install Pygame using pip:
Creating Buttons
Button Setup
Rectangular buttons have 4 different properties:
x (the x coordinate)
y (the y coordinate)
width
height
Example:
# Rectangle Button Properties
button_x = 150
button_y = 100
button_width = 100
button_height = 50
Creating a Basic Pygame Window
Once Pygame is installed, let’s create a simple window. Read the code comments (text in green) to understand how the program works.
import pygame
# Step 1: Initialize Pygame
pygame.init()
# Step 2: Create a window
screen = pygame.display.set_mode((400, 300)) # Sets window dimensions
pygame.display.set_caption("My First Pygame Window") # Sets window name
# Step 3: Define colors
white = (255, 255, 255) # Background
red = (255, 0, 0) # Button
black = (0, 0, 0) # Text
# Step 4: Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Checks if window closes
running = False
# Step 5: Fill the screen with a color
screen.fill((255, 255, 255)) # White background
pygame.display.flip() # Update the screen
# Step 6: Quit Pygame when window closes
pygame.quit()
Key Explanations:
pygame.init()
: Initializes all the Pygame modules required to use its built-in functions like window creation and event handling.pygame.display.set_mode()
: Creates the window for your Pygame application and defines its dimensions.pygame.display.set_caption()
: Sets the title of the window. In this case, "My First Pygame Window."pygame.event.get()
: Retrieves a list of all events (such as mouse clicks or key presses) that have occurred since the last time it was called.if event.type == pygame.QUIT:
: Checks if the event is a quit event (when the user closes the window).screen.fill()
: Fills the screen with a color (white in this case) to clear the screen before drawing anything new.pygame.display.flip()
: Updates the window with any changes made to the screen, like drawing a background or other graphics.pygame.quit()
: Uninitializes all Pygame modules and safely shuts down Pygame.
The Main Loop:
The main loop keeps the program running and continuously checks for events (e.g., user input) and updates the window. Inside the loop:
Event Handling: The program listens for events and handles them, such as closing the window when the quit event is triggered.
Drawing and Updating: The screen is cleared, and any changes or drawings are made before updating the display using
pygame.display.flip()
.
This cycle repeats until the user decides to close the window.
Add Text to the Button
To add text to buttons, you have to setup the font and draw the button text in the Main Loop.
# Setting up font
font = pygame.font.Font(None, 36) # Default font, size 36
# Draw the button (Main Loop)
black = (0, 0, 0)
text = font.render("Click Me", True, black)
text_rect = text.get_rect(center=(button_x + button_width // 2, button_y + button_height // 2))
screen.blit(text, text_rect) # Place text on button
Button Clicked Conditional
To make the button interactive, you need to check if the user clicks inside the button's boundaries during the main loop. Here's how you can add a condition to detect a button click:
# Inside the Main Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN: # Check for mouse click
mouse_x, mouse_y = event.pos # Get mouse position
if (button_x <= mouse_x <= button_x + button_width and
button_y <= mouse_y <= button_y + button_height):
print("Button Clicked!")
Key Explanations:
event.type == pygame.MOUSEBUTTONDOWN:
This condition checks if a mouse button is pressed, allowing the program to detect mouse clicks.mouse_x, mouse_y = event.pos
:This
sets the current position of the mouse when the button is clicked to mouse_x and mouse_yif (button_x <= mouse_x <= button_x + button_width and button_y <= mouse_y <= button_y + button_height):
This conditional checks if the mouse coordinates (mouse_x
,mouse_y
) are within the boundaries of the button.
Drawing the Button
To draw the button, you use the pygame.draw.rect() function inside Main Loop which takes the following parameters (inputs):
screen
color
Rectangular button properties
Example:
# Draw Button
pygame.draw.rect(screen, red, (button_x, button_y, button_width, button_height))
Mini Challenge
Download the starter file here.
Part 1: Add a Counter to Track Clicks
Add a text label that displays the number of times the button has been clicked.
Create a
click_count
variable and initialize it to 0.Update
click_count
each time the button is clicked.Render the updated
click_count
usingpygame.font.Font
.
Part 2: Hover Effect for the Button
Make the button's color change to a darker shade when the mouse is hovering over it.
Use
pygame.MOUSEMOTION
to track the mouse position.Check if the mouse position is inside the button's boundaries.
Update the
button_color
accordingly.