ppizarror / pygame-menu

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

How check value for text_input? #477

Open Poleg44 opened 7 months ago

Poleg44 commented 7 months ago

I do time widget with text_input for sec. How can i use onchange event for control sec value <=59? I need example with onchange event using.

ppizarror commented 7 months ago

Hi @Poleg44. You have many tools for controlling the values of inputs. In this case, you can use a combination of maxchar, input_type, and an on_change callback.

Maxchar limits the user to enter numbers greater than 99. Input type restricts input chars only to numeric, and on_change validates the time and responds appropriately. See the following example:

import pygame_menu
from pygame_menu.examples import create_example_window
from pygame_menu.locals import INPUT_INT

surface = create_example_window('Time validator', (600, 400))

# Create the menu
menu = pygame_menu.Menu(height=300, theme=pygame_menu.themes.THEME_DARK, title='Test timer', width=400)

# Add the input time entry and validate
time_input = menu.add.text_input('Time: ', input_type=INPUT_INT, maxchar=2)
def validate_time(value, *args):
    if value < 0:
        time_input.set_value(0)
    elif value > 59:
        time_input.set_value(59)
time_input.set_onchange(validate_time)

menu.add.button('Quit', pygame_menu.events.EXIT)
menu.mainloop(surface)

In the example, the time is validated; if less than 0, set 0; if greater than 59, set 59. There are better solutions, like building your own Widget based on TextInput. But I guess this works, and it is quite simple.

Greetings,