How to make a string’s content appears on screen as we type on keyboard?

I have this function, where player can type his name, but I want each letter to appear on the screen as he types them.
Here is my function :

def input_player_name():
    player_name_screen = True
    name = ""
    win.blit(player_name_bg, (0, 0))
    while player_name_screen:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    print(name)
                    player_name_screen = False
                else:
                    name += event.unicode                 
        pygame.display.update()
        clock.tick(fps)

If I write print(name)right after name+=event.unicode, each thing typed appears in the console. Do I have to use something like this

textsurface = game_font.render(str(name), False, (255, 255, 255))
    win.blit(textsurface, (0, 0))

and make it update each time something new goes into name?
Thanks for your help

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can either use pygame.font or pygame.freetype. In the following I use
pygame.font.
Waht you have to do is to generate a font object and render the text to a pygame.Surface (name_surf). This surface has to be blit to the window continuously in the loop. When the name changes, the the surface has to be recreated:

mizw8

import pygame
import pygame.font

pygame.init()

win = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
fps = 60

def input_player_name():
    # create font and text surface
    font = pygame.font.SysFont(None, 100)
    name_surf = font.render('', True, (255, 0, 0))
    player_name_screen = True
    name = ""
    while player_name_screen:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    player_name_screen = False
                else:
                    name += event.unicode
                    # recreate text surface   
                    name_surf = font.render(name, True, (255, 0, 0))              

        win.blit(player_name_bg, (0, 0))
        # blit text to window
        win.blit(name_surf, (50, 50))
        pygame.display.update()
        clock.tick(fps)

input_player_name()


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x