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 use only widgets, without menu? #438

Closed Merklins closed 1 year ago

Merklins commented 1 year ago

Hi, i want to use widgets as controls in my game, but I only need to use them without drawing menus. Because then it will block everything drawn by pygame, or vice versa. I've tried drawing and updating widgets and they work, but I just can't change their position at all using the translate method. This method works only for the first created button, not for the others.

start_button = main_menu.add.button('Start_game', action=lambda: sys.exit())
start_button.translate(-100, 0)

quit_button = main_menu.add.button('Quit_game', action=lambda: sys.exit())
quit_button.translate(100, 0)

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    start_button.draw(screen)
    start_button.update(events)

    quit_button.draw(screen)
    quit_button.update(events)
ppizarror commented 1 year ago

Hi! As you're not using the menu, you must manually "render" this object (even if you are not explicitely drawing it). See the menu as a smart container, it updates the position of the widgets, among others.

In your example, use the following:

# Note I disabled vertical center to have a consistent position
menu = Menu(..., title='Example menu', center_content=False)

# Your widgets
start_button = main_menu.add.button('Start_game', action=lambda: sys.exit())
start_button.translate(-100, 0)

quit_button = main_menu.add.button('Quit_game', action=lambda: sys.exit())
quit_button.translate(100, 0)

# Force the render
main_menu.render()

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    menu.update(events) # You should still update the menu, else, the selected item would not be updated, and so on...

    pygame.display.update()
    start_button.draw(screen)
    # start_button.update(events) Already updated by the menu

    quit_button.draw(screen)
    # quit_button.update(events) Already updated by the menu
Merklins commented 1 year ago

Great, that's what I need, thanks