【问题标题】:How to make a string's content appears on screen as we type on keyboard? [duplicate]当我们在键盘上键入时,如何使字符串的内容出现在屏幕上? [复制]
【发布时间】:2020-06-12 19:00:37
【问题描述】:

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

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)

如果我在name+=event.unicode 之后写print(name),则键入的每个内容都会出现在控制台中。我必须使用这样的东西吗

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

并在每次有新内容进入name 时更新它? 感谢您的帮助

【问题讨论】:

    标签: python string pygame


    【解决方案1】:

    您可以使用pygame.fontpygame.freetype。在下面我使用 pygame.font.
    你要做的就是生成一个font 对象并将文本渲染到pygame.Surface (name_surf)。这个表面必须是blit 到窗口连续循环。当名称更改时,必须重新创建表面:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 2016-06-04
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多