How to manage text input in pygame and in the cmd

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

the added code to make it a little better, going to the next line in the cmd

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.