Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Create the buttons in a game using Pygame
2.1.
Pygame
2.2.
Steps
2.3.
Code
2.4.
About the button
2.5.
Output: 
3.
Frequently Asked Questions
3.1.
Does pygame have a button?
3.2.
How might you let me know if the pygame button is squeezed?
3.3.
How would you make a stop button in pygame?
3.4.
How would you get keys in pygame?
3.5.
What text styles are in pygame?
4.
Conclusion
Last Updated: Mar 27, 2024

Create the buttons in a game using Pygame

Author Adya Tiwari
0 upvote

Introduction

Pygame doesn't really have some sort of button gadget that you might hope to find in a GUI library like Tkinter or PyQt5. Nonetheless, utilizing various elements, we can assemble something the same. The primary thing to do is to make the natural appearance of the button. This incorporates the text, variety, and state of the controller.

Create the buttons in a game using Pygame

A game priority interactable buttons have some control over various occasions to make the game more controlled and add an appropriate GUI to it. These can be made in pygame by making a square shape onto the screen and then superimposing the demonstrating text. We will utilize different capacities like draw.rect(), screen.blit(), and so forth. To add more energy to it, we can change the shade of the button as the mouse has drifted on it.

Pygame

To start with this, we must have some prior knowledge of the Pygame library.

Pygame is a Python library that can be utilized explicitly to plan and assemble games. Pygame backs 2D games constructed using various shapes/pictures called sprites. Pygame isn't incredibly best for planning games. It is highly mind-boggling to utilize and misses the mark on legitimate GUI like solidarity gaming motor; however, it certainly fabricates rationale for additional, more extensive undertakings.

Before instating the pygame library, we want to introduce it. This library can be introduced into the framework by utilizing the pip apparatus given by Python to its library establishment.

Steps

  • make an essential window
  • create a class for the Button
  • render the text to show on the button
  • create a surface with the size of the text
  • give the surface a variety (or a picture as foundation… I can make this in another post)
  • blit the reader on a superficial level
  • create a strategy to change the text of the button (when you click, for instance)
  • blit the button.surface on the screen
  • block snap of the mouse

Now back to making the button colorful and interactive, we utilize a capacity that refreshes the x and y position of the mouse pointer and puts away it as a tuple in a variable. Then, at that point, we can define the limits of the square shape into individual factors and check to assume the mouse is within those limits. Provided that this is true, the shade of the square will be changed to a lighter shade to show that the button is interactable.
It is recalling that the reality behind the button is significant. It isn't so much that clicking that text or hued box will initiate the capacity. It's the demonstration of clicking that particular region on the screen that makes it happen. Regardless of whether you were to eliminate the text and variety, that region of the screen would, in any case, be interactive.

Code

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()
You can also try this code with Online Python Compiler
Run Code

About the button

We know how to draw square shapes, so that we can do that. We likewise know how to add text to the screen and focus it, so there's that. Contained in there were our mouse position and activities. With that, we can know when a client has clicked inside the limits of our button without a doubt. We might take it further and make our controls "intuitive" to a mouse floating over them.
A practical method for making buttons on pygame (in python) is by introducing the bundle called pygame_widgets (pip3 introduce pygame_widgets) on Mac or Linux and (pip introduce pygame_widgets) on Windows. Furthermore, ensure you have pip introduced; if not, it won't work.

Output: 

This is what the buttons could look like

create-button-pygame-python

Frequently Asked Questions

Does pygame have a button?

Pygame doesn't have some sort of button gadget that you might hope to find in a GUI library like Tkinter or PyQt5. Nonetheless, utilizing a mix of elements, we can assemble something comparable.

How might you let me know if the pygame button is squeezed?

The capacity pygame. mouse. get_pressed() returns a tuple addressing assuming that the mouse buttons (left, mouse-wheel, right) are being squeezed or not.

How would you make a stop button in pygame?

Call pygame. Stop () to close down pygame (this incorporates shutting the window) Call sys. Exit () to close down the program (this leaves the endless circle).

How would you get keys in pygame?

type == pygame. KEYUP: if occasion. mod == pygame. KMOD_NONE: print('No modifier keys were in a squeezed state when this ' 'occasion happened.

What text styles are in pygame?

In conclusion, to stack a text-style document that isn't a TrueType textual style, you can utilize the pygame. FreeType module which upholds TTF, Type1, CFF, OpenType, SFNT, PCF, FNT, BDF, PFR and Type42 text styles.

Conclusion

In conclusion, we have learned that game-high priority interactable buttons have some control over various occasions in the game to make the game more controlled and add an appropriate GUI. This should be possible by utilizing a capacity that refreshes the x and y position of the mouse pointer and putting away it as a tuple in a variable. Then, at that point, we can define the limits of the square shape into individual factors and check to assume the mouse is within those limits. Assuming this is the case, the shade of the square will be changed to a lighter shade to demonstrate that the button is interactable.

Hey Ninjas! Don’t stop here; check out Coding Ninjas for Python, more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems. To learn more about Pygame, try this

Happy Learning!

Live masterclass