ppizarror / pygame-menu

A menu for pygame. Simple, and easy to use
https://pygame-menu.readthedocs.io/
Other
544 stars 141 forks source link

question: how to disable a button? #444

Closed ALfahi closed 1 year ago

ALfahi commented 1 year ago

hello I was wondering if I could disable a button from going to another submenu depending on the user input. I have a menu with a few text boxes and a button which leads to a different submenu. I was wondering if I I can disable the button from leading to the submenu if the values entered into the textboxes are left empty or if the values are not in the right format(for emails), etc.

If there are values entered into the text boxes( which are all correct and in the right format, etc) the button would allow the user to go the other submenu.

ALfahi commented 1 year ago

never mind; I have found a solution due to the previous enhancements: the solution was to make the button read-only and then change it with if statements. Thank you for this wonderful pip installation

ppizarror commented 1 year ago

I arrived late, but check the following example I just did:

import random
import pygame
import pygame_menu

pygame.init()
screen = pygame.display.set_mode((640, 480))
theme = pygame_menu.themes.THEME_BLUE.copy()
theme.widget_margin = (0, 5)
menu = pygame_menu.Menu('Button disable', 640, 480, theme=theme)

def check_name(name_value: str = '') -> None:
    """
    Checks the name, which updates the button.
    For complex mechanisms, you can use a class to store the name variable
    instead of accesing global ones (like this case).

    :param name_value: Value passed from onchange() text input method
    """
    global button
    name_ready = name_value != ''
    print('User not configured yet' if not name_ready else 'User ready!')
    button.readonly = not name_ready
    button.set_selection_effect(None if not name_ready else theme.widget_selection_effect)

def game() -> None:
    """
    Starts the game, this method only changes the background color of the menu.
    """
    print('Game started!')
    menu.get_scrollarea().update_area_color((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

# Create a basic input
name = menu.add.text_input('Enter your name: ', onchange=check_name)
button = menu.add.button('Play', game)
menu.add.button('Exit', pygame_menu.events.EXIT)

# Call start game to setup the initial status, it retrieves the name (which is empty at the app start),
# and disables the button by setting readonly, also dynamically updates the selection effect
check_name()
menu.mainloop(surface=screen)

This example retrieves the input and changes the color of the background color of the "menu area".

ALfahi commented 1 year ago

Thank you for the reply; I have found a way towards a solution using the readonly feature of a button; this example is also very helpful and is exactly what I needed; thank you once again I appreciate it a lot