The Wayback Machine - https://web.archive.org/web/20240623173841/https://www.geeksforgeeks.org/how-to-create-buttons-in-a-game-using-pygame/
Open In App

How to create Buttons in a game using PyGame?

Last Updated : 08 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming engine but it definitely builds logic for further larger projects.

Installation

Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal.

pip install pygame

Creating interactable buttons using pygame

A game must have interactable buttons that can control different events in the game to make the game more controlled and to add a proper GUI in it. These can be created in pygame by creating a rectangle onto the screen and then superimposing the indicating text on it. For this, we will be using various functions like draw.rect(), screen.blit() etc. To add more liveliness to it we can change the color of the button as the mouse has hovered on it.

This can be done by using a function that updates the x and y position of the mouse pointer and storing it as a tuple in a variable. Then we can set the boundaries of the rectangle into respective variables and check if the mouse is in those boundaries if so the color of the block will be changed to lighter shade to indicate that the button is interactable.

Below is the implementation.




import pygame
import sys
  
  
# initializing the constructor
pygame.init()
  
# screen resolution
res = (720,720)
  
# opens up a window
screen = pygame.display.set_mode(res)
  
# white color
color = (255,255,255)
  
# light shade of the button
color_light = (170,170,170)
  
# dark shade of the button
color_dark = (100,100,100)
  
# stores the width of the
# screen into a variable
width = screen.get_width()
  
# stores the height of the
# screen into a variable
height = screen.get_height()
  
# defining a font
smallfont = pygame.font.SysFont('Corbel',35)
  
# rendering a text written in
# this font
text = smallfont.render('quit' , True , color)
  
while True:
      
    for ev in pygame.event.get():
          
        if ev.type == pygame.QUIT:
            pygame.quit()
              
        #checks if a mouse is clicked
        if ev.type == pygame.MOUSEBUTTONDOWN:
              
            #if the mouse is clicked on the
            # button the game is terminated
            if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
                pygame.quit()
                  
    # fills the screen with a color
    screen.fill((60,25,60))
      
    # stores the (x,y) coordinates into
    # the variable as a tuple
    mouse = pygame.mouse.get_pos()
      
    # if mouse is hovered on a button it
    # changes to lighter shade 
    if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40:
        pygame.draw.rect(screen,color_light,[width/2,height/2,140,40])
          
    else:
        pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40])
      
    # superimposing the text onto our button
    screen.blit(text , (width/2+50,height/2))
      
    # updates the frames of the game
    pygame.display.update()


Output:

create-button-pygame-python



Previous Article
Next Article

Similar Reads

Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
Create a Memory Puzzle Game Using Pygame
Playing memory puzzle games provides entertainment and boosts mental abilities such as focus and memory recall. This article guides you through the steps to create a straightforward memory puzzle game using the Python Pygame Library. After completing the article, you will have a fully functioning game where players try to match pairs of game pieces
10 min read
Create a Pong Game in Python - Pygame
Pong is a table tennis-themed 2-player 2D arcade video game developed in the early 1970s. The game consists of two paddles/strikers, located at the left and right edges of the screen, and a ball. Create a Pong Game in PythonThe basic theme of this game is to make sure that the ball doesn't hit the wall behind you. If it does, the opponent scores a
10 min read
8-bit game using pygame
Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesn’t have a proper GUI like unity but it definitely builds logic for further complex projects.We’ll be creating
9 min read
Building and visualizing Sudoku Game Using Pygame
Sudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contain all of the digits from 1 to 9. We will be building the Sudoku Game in python using pygame library and automate the game using backtracking algo
7 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer s
15+ min read
Spiral Sprint Game in Python Using Pygame
In this article, we will see how to create a spiral sprint game in Python using Pygame. In this game, we will have functionality like difficulty modes, obstacle crashing, speed increment when points are increased, scoreboard, Particle animation, color-changing orbits, coins, and game sounds. Spiral Sprint Game in Python Using PygameBefore going any
15+ min read
Stimulate bouncing game using Pygame
In this article, we will learn to make a bouncing game using Pygame. Pygame is a set of Python modules designed for writing video games. It adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the Python language. It is free and runs on nearly every platform and operating
4 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Angry Bird Game Using PyGame
Let's discuss the angry bird game using Pygame, I hope this article will be very interesting as it provides a holistic gaming experience at the end. We begin by describing the modules necessary to develop this game. Angry Birds Game Using PyGame The objective of the game is to hit as many enemy birds as possible to score points. Your score increase
14 min read
Practice Tags :
three90RightbarBannerImg