Search code examples
pythonpygametextboxpygame-gui

Text inside a pygame_gui textbox disappears after changing it - pygame_gui library


I am using the pygame_gui library. I am trying to make a textbox that when pressed enter it will print the text inside the box to the console and reset it (so the textbox will be empty). It does indeed resets the textbox but for some reason the textbox doesnt get any new input until I click somewhere in the background and click again on the textbox and only then it shows the text it gets.

The code:

import pygame_gui, pygame

pygame.init()
screen = pygame.display.set_mode((500,500))

clock = pygame.time.Clock()
manager = pygame_gui.UIManager((500,500))
manager.set_window_resolution((500,500))

text_box = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(200,200,100,50), manager=manager, object_id='#text')

run=True
while run:
    UI_refresh = clock.tick(30)/1000

    for event in pygame.event.get():
        if event.type==pygame.QUIT: run=False
        elif event.type==pygame_gui.UI_TEXT_ENTRY_FINISHED and event.ui_object_id == '#text':
            print(text_box.text)
            text_box.set_text('') #here the text of the texbox is reset.

        manager.process_events(event)
    manager.update(UI_refresh)

    screen.fill('white')
    manager.draw_ui(screen)

    pygame.display.update()

I tried instead of reseting the textbox to set the text of it to some other value like 'A' (I changed the line text_box.set_text('') to text_box.set_text('A') ) but the textbox was still shown to be empty for some reason and I had the same problem.

Plus I should mention that when setting the text it does show the changes for a bit less than a second before it disappears until I click somewhere on the screen and again on the textbox to show the changes.


Solution

  • I have gone through the source and I found out that if we add the line text_box.redraw() right after the set_text it fixes the problem, so the updated code is:

    import pygame_gui, pygame
    
    pygame.init()
    screen = pygame.display.set_mode((500,500))
    
    clock = pygame.time.Clock()
    manager = pygame_gui.UIManager((500,500))
    manager.set_window_resolution((500,500))
    
    text_box = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect(200,200,100,50), manager=manager, object_id='#text')
    
    run=True
    while run:
        UI_refresh = clock.tick(30)/1000
    
        for event in pygame.event.get():
            if event.type==pygame.QUIT: run=False
            elif event.type==pygame_gui.UI_TEXT_ENTRY_FINISHED and event.ui_object_id == '#text':
                print(text_box.text)
                text_box.set_text('') #here the text of the texbox is reset.
                text_box.redraw() #this line fixes the problem.
    
            manager.process_events(event)
        manager.update(UI_refresh)
    
        screen.fill('white')
        manager.draw_ui(screen)
    
        pygame.display.update()