Open In App

Create Settings Menu in Python – Pygame

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a flexible programming language with a large selection of libraries and modules for a variety of applications. Pygame menu is one such toolkit that enables programmers to design graphical user interfaces for games and apps. In this tutorial, we’ll look at how to use the pygame menu package to build a simple options menu. Users will have choices to alter game settings including the sound, music, and level of difficulty through this menu.Pygame_menu is a Python-Pygame library used to create menus and GUIs. You will have a working options menu at the end of this tutorial, which you can incorporate into your pygame-based game or application to make it more interactive and user-customizable.

Architecture Of Application 

The architecture of this application consists of two parts: Main Menu and the Settings Menu

Main Menu :

Main Menu

Settings Menu :

Settings Menu

Installation of Pygame and Pygame_menu 

To install Pygame on windows, simply type the following command on the Terminal:

pip install pygame

To install pygame_menu on windows, simply type the following command on the Terminal

pip install pygame_menu

Building the initial application 

Before we build the actual application, first let’s see how to get started with the library by building a basic window with a single label on it using the following code.

Python3




# Program to create a basic window using the pygame_menu module
  
import pygame
import pygame_menu as pm
  
pygame.init()
  
WIDTH, HEIGHT = 700, 600
  
# Screen and caption
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Window using Pygame_menu")
  
  
# Main Function
def mainFun():
    # Creating a menu
    menu = pm.Menu(title="Main Menu",
                   width=WIDTH,
                   height=HEIGHT,
                   theme=pm.themes.THEME_GREEN)
  
    # Adding a label to the menu
    menu.add.label(title="This is a label on the Main Menu")
  
    # Displaying the menu on the screen using the "mainloop" method of pygame_menu.Menu
    menu.mainloop(screen)
  
  
if __name__ == "__main__":
    mainFun()   # Calling the main function
  
  
# This code is contributed by Teja


Output: 

Basic window

Explanation:

  1. Import the required modules and initialize them.
  2. Create the screen using the pygame.display.set_mode() method
  3. Now declare a main function and create a menu using the pygame_menu.Menu() method
  4. This method takes in several parameters. However, there are three main parameters in this method: “title”, “width”, and “height”.
    title: This is the name that is displayed on the top left corner of the screen. In our case, the title is set as “Main Menu”
    width and height: They are set to the width and height of the screen respectively.
  5. An optional argument passed to the method is the “theme”. There are various possible themes available in pygame_menu.
  6. After creating a menu, we add a label to it using the add.label() method. We pass the content that is to be written on the label as an argument to the label’s “title” parameter.
  7. After adding all the widgets, we display this menu on the screen using the mainloop() method. This method takes in the screen, that we defined earlier, as the argument and loops this menu on it.

Building the Pygame menu application

This consists of two parts : 

  1. Building the main menu
  2. Building the settings menu

1) Building the Main Menu

The first part is to build the main menu with the proposed design

Python3




import pygame
import pygame_menu as pm
  
pygame.init()
  
# Screen
WIDTH, HEIGHT = 700, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
  
# Standard RGB colors
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 100, 100)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
  
# Main Function
def mainFun():
    mainMenu = pm.Menu(title="Main Menu",
                       width=WIDTH,
                       height=HEIGHT,
                       theme=pm.themes.THEME_GREEN)
  
    # Settings button. If clicked, it takes to the settings menu
    mainMenu.add.button(title="Settings", font_color=WHITE,
                        background_color=GREEN)
  
    # Dummy label to add some spacing between the settings button and exit button
    mainMenu.add.label(title="")
  
    # Exit Button. If clicked, it closes the window
    mainMenu.add.button(title="Exit", action=pm.events.EXIT,
                        font_color=WHITE, background_color=RED)
  
    mainMenu.mainloop(screen)
  
  
if __name__ == "__main__":
    mainFun()


Output:

Main Menu

Explanation:

  1. We create the window and name it accordingly using the previously mentioned steps.
  2. Now, we add a settings button using the add.button() method.
  3. To this method, we pass the text that is to be rendered upon it, the font color, and the background color.
  4. Now, we add an empty label using the add.label() method. This label is just used to add some spacing between the settings button and the exit button.
  5. After this, we add an exit button in the same way as we added the settings button but with an extra argument i.e., “action“.
  6. Usually, a function or a menu is passed as an argument to the action parameter. So, when the button is clicked, it runs the given function or switches to the given menu.
  7. So, when the exit button is clicked, the window closes.

2) Building the Settings Menu

Now let’s create the settings menu as per the proposed design –

Python3




# Python program to create a basic settings menu using the pygame_menu module
  
import pygame
import pygame_menu as pm
  
pygame.init()
  
# Screen
WIDTH, HEIGHT = 700, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
  
# Standard RGB colors
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 100, 100)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
  
# Main function of the program
  
  
def main():
    # List that is displayed while selecting the graphics level
    graphics = [("Low", "low"),
                ("Medium", "medium"),
                ("High", "high"),
                ("Ultra High", "ultra high")]
  
    # List that is displayed while selecting the window resolution level
    resolution = [("1920x1080", "1920x1080"),
                  ("1920x1200", "1920x1200"),
                  ("1280x720", "1280x720"),
                  ("2560x1440", "2560x1440"),
                  ("3840x2160", "3840x2160")]
  
    # List that is displayed while selecting the difficulty
    difficulty = [("Easy", "Easy"),
                  ("Medium", "Medium"),
                  ("Expert", "Expert")]
  
    # List that is displayed while selecting the player's perspective
    perspectives = [("FPP", "fpp"),
                    ("TPP", "tpp")]
  
    # This function displays the currently selected options
  
    def printSettings():
        print("\n\n")
        # getting the data using "get_input_data" method of the Menu class
        settingsData = settings.get_input_data()
  
        for key in settingsData.keys():
            print(f"{key}\t:\t{settingsData[key]}")
  
    # Creating the settings menu
    settings = pm.Menu(title="Settings",
                       width=WIDTH,
                       height=HEIGHT,
                       theme=pm.themes.THEME_GREEN)
  
    # Adjusting the default values
    settings._theme.widget_font_size = 25
    settings._theme.widget_font_color = BLACK
    settings._theme.widget_alignment = pm.locals.ALIGN_LEFT
  
    # Text input that takes in the username
    settings.add.text_input(title="User Name : ", textinput_id="username")
  
    # 2 different Drop-downs to select the graphics level and the resolution level
    settings.add.dropselect(title="Graphics Level", items=graphics,
                            dropselect_id="graphics level", default=0)
    settings.add.dropselect_multiple(title="Window Resolution", items=resolution,
                                     dropselect_multiple_id="Resolution",
                                     open_middle=True, max_selected=1,
                                     selection_box_height=6)
  
    # Toggle switches to turn on/off the music and sound
    settings.add.toggle_switch(
        title="Muisc", default=True, toggleswitch_id="music")
    settings.add.toggle_switch(
        title="Sounds", default=False, toggleswitch_id="sound")
  
    # Selector to choose between the types of difficulties available
    settings.add.selector(title="Difficulty\t", items=difficulty,
                          selector_id="difficulty", default=0)
  
    # Range slider that lets to choose a value using a slider
    settings.add.range_slider(title="FOV", default=60, range_values=(
        50, 100), increment=1, value_format=lambda x: str(int(x)), rangeslider_id="fov")
  
    # Fancy selector (style added to the default selector) to choose between 
    #first person and third person perspectives
    settings.add.selector(title="Perspective", items=perspectives,
                          default=0, style="fancy", selector_id="perspective")
  
    # clock that displays the current date and time
    settings.add.clock(clock_format="%d-%m-%y %H:%M:%S",
                       title_format="Local Time : {0}")
  
    # 3 different buttons each with a different style and purpose
    settings.add.button(title="Print Settings", action=printSettings,
                        font_color=WHITE, background_color=GREEN)
    settings.add.button(title="Restore Defaults", action=settings.reset_value,
                        font_color=WHITE, background_color=RED)
    settings.add.button(title="Return To Main Menu",
                        action=pm.events.BACK, align=pm.locals.ALIGN_CENTER)
  
    # Creating the main menu
    mainMenu = pm.Menu(title="Main Menu",
                       width=WIDTH,
                       height=HEIGHT,
                       theme=pm.themes.THEME_GREEN)
  
    # Adjusting the default values
    mainMenu._theme.widget_alignment = pm.locals.ALIGN_CENTER
  
    # Button that takes to the settings menu when clicked
    mainMenu.add.button(title="Settings", action=settings,
                        font_color=WHITE, background_color=GREEN)
  
    # An empty label that is used to add a seperation between the two buttons
    mainMenu.add.label(title="")
  
    # Exit button that is used to terminate the program
    mainMenu.add.button(title="Exit", action=pm.events.EXIT,
                        font_color=WHITE, background_color=RED)
  
    # Lets us loop the main menu on the screen
    mainMenu.mainloop(screen)
  
  
if __name__ == "__main__":
    main()


app.py

Output :

Settings Menu

Explanation :

  1. First, we create a new “settings” menu in the same way we created the main menu. and then add the “action=settings” argument to the main menu.
  2. To this settings menu, first, we add a text input field, “User Name”, using the add.text_input() method. This method creates a text input field that reads the entered value. To this method, we pass the title (User Name) and its id.
  3. Now, we add a drop-down widget, “Graphics Level”, using the add.dropselect() method. To this method, we pass the title (Graphics Level), items to display (graphics list that was previously defined), default value (0 indicates the first item in the list), and its id .
  4. Now, we create a drop down widget, “Window Resolution”, that lets us select multiple values using the add.dropselect_multiple() method. To this method, we pass the title (Window Resolution), items to display (resolution list that was previously defined), open_middle (if set to true, then the drop down appears in the center of the screen), max_selected (The number of options you can select),  and the selection_box_height (height of the drop down) and its id.
  5. Now we add two toggle buttons, “Music” and “Sounds”, using the add.toggle_switch() method. This method only takes in the title (music or sounds), the default value (on/off), and the id as the arguments.
  6. Now, we add a selector, “Difficulty”, using the add.selector() method. This method takes the title (Difficulty), items to be displayed (difficulty list that was previously defined), default value (0 indicates the first element of the list) and its id as the arguments.
  7. Now, we add a range_slider, “FOV”, using the add.range_slider() method. This method takes the title (FOV), range_values (min and max values of the slider), default value (initial value of the slider), increment (number of steps to increase while dragged along its length) and its id as the arguments.
  8. Now, we add a different type of selector, “Perspective”, using the add.selector() method. This is similar to the Difficulty selector that we created earlier. The only difference is the style of this selector. Using an extra argument style=”facny”, we can create a different type of selector.
  9. Now, we add a clock, “Local Time”, using the add.clock() method. This method takes the clock_format (DD-MM-YY) and the title_format as the arguments and returns a clock that shows the local time.
  10. Now, we add a button, “Print Settings”, using the add.button() method. This button prints the current values in all the widgets using the “printSettings” function.
  11. printSettings” function gets the data using “get_input_data” method of the Menu class and it stored in a key-value format. So, iterating through the keys (widget id) gives us its corresponding values (widget value).
  12. Now, we add a new button, “Restore Defaults”, using the add.button() method. This is used to reset the values entered and restore the default values. This is done using the reset_value method of the menu class.
  13. Finally, we add another button, “Return To Main Menu”, using the add.button() method. This button is used to return back to the main menu.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads