pythonsliderpygame-widgets

Why I can't click the sliders?


I created a pygame code to simulate Turing Patterns. I wanted to add sliders to update the variables while the simulation working but they don't work at all. When I click the screen it freezes and doesn't respond.

pygame.init()
w_width = 600
w_height = 600

screen = pygame.display.set_mode([w_width, w_height])

ra = 3
ri = 5
wa = 1
wi = 0.2

screen.fill((128, 128, 128))
model = Model(rows,cols, ra, ri, wa, wi, 0.5)
model.drawGrid(screen, w_width, w_height)

slider_wa = Slider(screen, 40, 20, 50, 10, min=0, max=2, step=0.1)
output_wa = TextBox(screen, 5, 10, 25, 25, fontSize=15)
output_wa.disable()

slider_wi = Slider(screen, 140, 20, 50, 10, min=0, max=2, step=0.1)
output_wi = TextBox(screen, 105, 10, 25, 25, fontSize=15)
output_wi.disable()  

slider_ra = Slider(screen, 250, 20, 50, 10, min=0, max=10, step=0.5)
output_ra = TextBox(screen, 215, 10, 25, 25, fontSize=15)
output_ra.disable()

slider_ri = Slider(screen, 360, 20, 50, 10, min=0, max=10, step=0.5)
output_ri = TextBox(screen, 325, 10, 25, 25, fontSize=15)
output_ri.disable()

ra = slider_ra.getValue()
ri = slider_ri.getValue()
wa = slider_wa.getValue()
wi = slider_wi.getValue()
    
running = True

time_delay = 100
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, time_delay )

win = pygame.display.set_mode([w_width, w_height])

while running:
    for event in pygame.event.get():   
        if event.type == QUIT:
            running = False
        
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                model.update()
                model.drawGrid(screen, w_width, w_height)
        if event.type == timer_event:
                model.update()
                model.drawGrid(screen, w_width, w_height)
                
    
    screen.fill((128, 128, 128))
                
    output_wa.setText(slider_wa.getValue())
    output_wi.setText(slider_wi.getValue())
    output_ra.setText(slider_ra.getValue())
    output_ri.setText(slider_ri.getValue())
    
    pygame_widgets.update(event)
    pygame.display.update()


pygame.quit()

I tried the code I got from pygame documentation( text) it is working well alone but I couldn't integrate it into my code.


Solution

  • You need to pass the list of events to pygame_widgets.update, but not a single event (see also Pygame Widgets. Calling pygame_widget outside the event loop with event does not do what you expect, because event always contains only the last event object in the queue, and thus not all events are passed to pygame_widget:

    while running:
    
        # get list of events
        events = pygame.event.get()
        
        # use the list of events in the event loop
        for event in events:   
            if event.type == QUIT:
                running = False
            # [...]
    
        # pass list of events to pygame widgets
        pygame_widgets.update(events)
    
    
        # [...]