在python中将键盘输入附加到变量

时间:2017-10-26 08:45:21

标签: python pygame append

我希望变量text = []附加键盘输入,然后打印出来。

import pygame
pygame.init()
screen = pygame.display.set_mode([600, 400])
keepGoing = True

def get_text ():
    keepText = True
    while keepText:
        text = [] # I want to add input here

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            keys = pygame.key.name(event.key)
            text.append(keys)
            print (text)
            if event.key == pygame.K_ESCAPE:
                keepText = False                   

  while keepGoing:                        
      for event in pygame.event.get():    
          if event.type == pygame.QUIT: 
              keepGoing = False
          if event.type == pygame.KEYDOWN:
              if event.key == pygame.K_SPACE:
                  get_text ()

          pygame.display.update()  

pygame.quit() 

我该怎么做?

2 个答案:

答案 0 :(得分:0)

我认为this question是您正在寻找的。你会想要像

这样的东西
while keepText:
    text = []
    text.append(raw_input('Input something from the keyboard: '))

在你的问题中,缩进看起来有问题,而你的while循环永远不会结束。

答案 1 :(得分:0)

如果发生pygame.KEYDOWN事件,您只需将其.unicode属性添加到字符串或将其附加到列表中即可。

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    text = ''

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                text += event.unicode
                print(text)

        screen.fill((30, 30, 30))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()