ppizarror / pygame-menu

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

Customizing the KEY_APPLY variable #410

Closed eforgacs closed 2 years ago

eforgacs commented 2 years ago

I would like to use either the Enter key or another key of my choice to select an option. Right now, from what I can tell, the only key allowed for this purpose is set in controls.py as KEY_APPLY = __locals.K_RETURN. Is there a way to customize the key used for this purpose?

ppizarror commented 2 years ago

Hi! I'll test a new object named "Controller" which accepts events and the object itself and must return true if accepts. For example

controller = Controller() MyWidget(): widget.set_controller(controller)

if self.controller.on_key_apply() or __locals.K_RETURN: do()

ppizarror commented 2 years ago

Finished :). The beauty of this new solution is that it keeps the simple usage of the library (a non-power-user might not need this new feature), is retro-compatible, and is easy to use. To change, for example, the apply button, the following can be added:

from pygame_menu.controls import Controller
from random import randrange
custom_controller = Controller()

def btn_apply(event, _):
    applied = event.key in (pygame.K_a, pygame.K_b, pygame.K_c)
    if applied:
        menu.get_scrollarea().update_area_color((randrange(0, 255), randrange(0, 255), randrange(0, 255)))
    return applied

custom_controller.apply = btn_apply
btn = menu.add.button('My button', lambda: print('Clicked!'))
btn.set_controller(custom_controller)
...

As you would expect. If pressed A, B, or C, the menu background color changes.

eforgacs commented 2 years ago

Perfect! Thanks so much :)

ppizarror commented 2 years ago

Merged to master. I've proposed also a new docs section. Any suggestion is appreciated.

Greetings :)