1

I want variable text = [] to append the keyboard input, and then print it.

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

How can I do this?

Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32

2 Answers2

0

I think this question is what you're looking for. You'll want something like

while keepText:
    text = []
    text.append(raw_input('Input something from the keyboard: '))

In your question the indenting looks problematic though, and your while loop will never end.

Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32
0

If a pygame.KEYDOWN event occurs, you can just add its .unicode attribute to a string or append it to a list.

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()
skrx
  • 19,980
  • 5
  • 34
  • 48