Let’s see ho to get a multi plie text input, from this video of Coding with Russ.
With the following code you will see on the console the key you press
import pygame pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode( (SCREEN_WIDTH,SCREEN_HEIGHT)) BG = (60, 114, 228) TEXT_COL = (246, 247, 246) run = True while run: screen.fill(BG) for event in pygame.event.get(): if event.type == pygame.TEXTINPUT: print(event.text) if event.type == pygame.QUIT: run = False pygame.display.flip()
Let’s add the chance to write more text instead of just one character per line.
import pygame import os pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode( (SCREEN_WIDTH,SCREEN_HEIGHT)) BG = (60, 114, 228) TEXT_COL = (246, 247, 246) text = "" run = True while run: screen.fill(BG) for event in pygame.event.get(): if event.type == pygame.TEXTINPUT: text += event.text os.system("cls") print(text) if event.type == pygame.QUIT: run = False pygame.display.flip()
Let’s add a cursor (run from cmd)
import pygame import os pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode( (SCREEN_WIDTH,SCREEN_HEIGHT)) BG = (60, 114, 228) TEXT_COL = (246, 247, 246) text = "" run = True while run: screen.fill(BG) for event in pygame.event.get(): if event.type == pygame.TEXTINPUT: os.system("cls") text += event.text print(text + "|") if event.type == pygame.KEYDOWN: if event.key == pygame.K_BACKSPACE: os.system("cls") text = text[:-1] print(text + "|") if event.type == pygame.QUIT: run = False pygame.display.flip()
Adjusting the code another bit.
import pygame import os pygame.init() SCREEN_WIDTH = 200 SCREEN_HEIGHT = 100 screen = pygame.display.set_mode( (SCREEN_WIDTH,SCREEN_HEIGHT)) BG = (60, 114, 228) TEXT_COL = (246, 247, 246) text = "" run = True while run: screen.fill(BG) for event in pygame.event.get(): if event.type == pygame.TEXTINPUT: os.system("cls") text += event.text print(text + "|") if event.type == pygame.KEYDOWN: if event.key == pygame.K_BACKSPACE: os.system("cls") text = text[:-1] print(text + "|") if event.key == pygame.K_RETURN: os.system("cls") text = text[:-1] text = text + "\n" print(text + "|") if event.type == pygame.QUIT: run = False pygame.display.flip()
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame