一尘不染

当我们在键盘上打字时,如何使字符串的内容出现在屏幕上?

python

我有这个功能,玩家可以输入他的名字,但我想要每个字母
在他打字时出现在屏幕上。我的职责是:

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)

如果我在名字后面写上“print(name)”+=事件.unicode`,每件事
出现在控制台中。我一定要用这种东西吗

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


阅读 281

收藏
2020-12-20

共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:

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()
2020-12-20