1

I'm writing a basic program with pygame that in some part needs to take an text input from the user. My problem is that when the user wants to erase part of the text, the old text keeps displaying it in the pygame window. Let's say the user types '23' and then presses backspace. The console shows 2 but the pygame window will keep displaying 23. I'm using:

if event.key == pg.K_BACKSPACE:
   text = text[:-1]
1
  • You have to (re)render the text surface after changing the text. Commented Jul 4, 2021 at 9:30

1 Answer 1

1

You have to (re)render the text surface after changing the text and you have to clear the display in every frame:


Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 200))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()

text = ""
text_surf = font.render(text, True, (0, 0, 0))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False  
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE: 
                text = text[:-1]
            else:
                text += event.unicode 
            text_surf = font.render(text, True, (0, 0, 0))        

    window_center = window.get_rect().center

    window.fill((255, 255, 255))
    window.blit(text_surf, text_surf.get_rect(center = window_center))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

The typical PyGame application loop has to:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.