Search code examples
pythonpygamepygame-gui

pygame_gui events not firing


I am trying to do something I have done before with no issue, that is use pygame_gui with pygame to detect when a UI button has been clicked.

import pygame as pg
import pygame_gui as pgg
import tkinter as tk
import tkinter.filedialog
import csv


character_dict = ()
last_character_gui = None


def main():
    pg.init()
    screen = pg.display.set_mode((800, 600))
    gui_manager = pgg.UIManager((800, 600))
    app_running = True
    clock = pg.time.Clock()
    open_file_button = pgg.elements.UIButton(relative_rect=pg.Rect(0, 0, 800, 50),
                                             manager=gui_manager,
                                             text="open file")
    scroll_container = pgg.elements.ui_scrolling_container.UIScrollingContainer(relative_rect=pg.Rect(0, 50, 800, 2000),
                                                                                manager=gui_manager)
    while app_running:
        time_delta = clock.tick(60) / 100.0
        gui_manager.update(time_delta)
        gui_manager.draw_ui(screen)
        pg.display.update()

        for event in pg.event.get():
            if event.type == pgg.UI_BUTTON_PRESSED:
                if event.ui_element == open_file_button:
                    file = prompt_file()
                    character_dict = populate_characters(file)
                    populate_gui(scroll_container, gui_manager)
            if event.type == pg.QUIT:
                app_running = False

The problem is that no UI_BUTTON_PRESSED event is ever firing. I have tried tracking the event output and it simply never occurs. I have tried reading the documentation, but alas I cannot see what I am doing wrong here or where the issues might be. I would greatly appreciate any help.


Solution

  • UI_BUTTON_PRESSED is not a Pygame event, but a Pygame GUI event. See GUI events - UI_BUTTON_PRESSED. The Pygame GUI events needs to be processed with process_events:

    for event in pg.event.get():
        gui_manager.process_events(event)