How to make a Main Menu in Pygame

Опубликовано: 04 Август 2026
на канале: Scripted Pixels HQ
23
1

This video goes through the basics for setting up a main menu in Pygame.

Notes:

If you plan on using a lot of buttons it is better use an array. This can be done by:

-Making a blank array called buttons
-Rather than making each buttun just do buttons.append("YOUR BUTTON")
-Then to display do:
for button in buttons:
button.draw()
button.hover()
do the same for clicks

This will make the code more streamlined and faster to write




FULL CODE:

import pygame

pygame.init()

class Button():
def __init__(self,x,y,width,height,colour,destination):
self.x = x
self.y = y
self.width = width
self.height = height
self.colour = colour
self.destination = destination
self.text = destination

self.rect = pygame.Rect(x,y,width,height)
self.hovercolour = tuple(max(0,i-50) for i in colour)

def draw(self):
pygame.draw.rect(Screen,self.colour,self.rect)
Font = pygame.font.Font(None,36)
text = Font.render(str(self.text),True,(0,0,0))
Screen.blit(text,(self.x + (self.width-text.get_width())//2,self.y + (self.height - text.get_height())//2))

def hover(self):
if self.rect.collidepoint(mouse_pos):
pygame.draw.rect(Screen,self.hovercolour,self.rect)
Font = pygame.font.Font(None,36)
text = Font.render(str(self.text),True,(0,0,0))
Screen.blit(text,(self.x + (self.width-text.get_width())//2,self.y + (self.height - text.get_height())//2))

def click(self):
global Menu
if self.rect.collidepoint(mouse_pos):
Menu = self.destination






SCREEN_WIDTH = 800
SCREEN_HEIGHT = int(0.8*SCREEN_WIDTH)

Screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))

pygame.display.set_caption("MAIN MENU")

ButtonWidth = 200
ButtonHeight = 50

PlayButton = Button((SCREEN_WIDTH-ButtonWidth)//2,SCREEN_HEIGHT//3,ButtonWidth,ButtonHeight,(0,200,0),"Play")
SettingsButton = Button((SCREEN_WIDTH-ButtonWidth)//2,SCREEN_HEIGHT//3 + 1*(10+ButtonHeight),ButtonWidth,ButtonHeight,(150,150,150),"Settings")
QuitButton = Button((SCREEN_WIDTH-ButtonWidth)//2,SCREEN_HEIGHT//3 + 2*(10+ButtonHeight),ButtonWidth,ButtonHeight,(200,0,0),"Quit")


running = True

Menu = "Main Menu"

while running:
mouse_pos = pygame.mouse.get_pos()

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if Menu == "Main Menu":
PlayButton.click()
SettingsButton.click()
QuitButton.click()


Screen.fill((200,200,200))

if Menu == "Main Menu":
TitleFont = pygame.font.Font(None,75)
Title = TitleFont.render("MAIN MENU", True, (0,0,0))
Screen.blit(Title,((SCREEN_WIDTH-Title.get_width())//2, 10))

PlayButton.draw()
SettingsButton.draw()
QuitButton.draw()

PlayButton.hover()
SettingsButton.hover()
QuitButton.hover()

if Menu == "Quit":
running = False



pygame.display.flip()
pygame.display.update()

pygame.quit()