Pygame Text Processing

I am trying to write a python/pygame program to simply display text. I want it to work so that when you type, for example, the letter "A", it appears on screen (kinda like gedit/notepad/whatever). I am doing this by appending the letter to a string which then gets rendered and put onto the screen. However, I have problems with actually getting user input. I know that there is the pygame.key.get_pressed() function, but I can only figure out how to use it if you actually know what key you want the user to be pressing (for example W to go forward), but not if I don't know. If that is confusing, here is my code:

import pygame
import sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600,500))
myfont = pygame.font.Font(None, 60)
inp = ""

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()
    inp = inp + #THE PRESSED KEY
    screen.fill((0,0,200))
    txt = myfont.render(inp, True, (255,255,255))
    screen.blit(txt, (100,100))
    pygame.display.update()

I want to figure out how to get the "pressed key" to get appended to the string.

1 Answer

You could use the KEYDOWN event for this because pygame.key.get_pressed() will give you results at the speed of the current FPS.

Here is a working example modified from your code:

import pygame
import sys
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600,500))
myfont = pygame.font.Font(None, 60)
inp = ""

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            inp += event.unicode

    screen.fill((0,0,200))
    txt = myfont.render(inp, True, (255,255,255))
    screen.blit(txt, (100,100))
    pygame.display.update()

Only changed this:

  • Removed you pygame.key.get_pressed() call
  • Added the pygame.KEYDOWN event check
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest