Kimbly  North
Kimbly North

Reputation: 405

how do I write a message on screen using keyboard input?

I want 1 to appear on the screen when I press 1. This code doesn't show any error messages and when I press 1 nothing happens.

import pygame

pygame.init()

disp_x = 200
disp_y = 300
size = 60
space = 15


white = (255,255,255)
black =(0,0,0)

gameDisplay = pygame.display.set_mode((disp_x,disp_y))
image = pygame.image.load('GREEN_BUBLES.png')
font = pygame.font.SysFont(None,50)
text = font.render("0",True,black)
while True:
gameDisplay.fill((white))
gameDisplay.blit(image,(0,0))
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_1:
            text = font.render("1",True,black)
gameDisplay.blit(text,(15,10))



pygame.display.update()
pygame.event.wait()

Upvotes: 0

Views: 66

Answers (1)

lain
lain

Reputation: 448

You can create a string and then appending to the end each key that correspond to a char you can display:

from pygame import init, display, font
from pygame.event import get as event_getter
from pygame.locals import *
from time import sleep
init ()
surf = display.set_mode ((400, 400))

string = ""
while 1:
  sleep (0.1)
  for event in event_getter ():
    if event.type == KEYDOWN:
      if event.key == K_BACKSPACE and string:
        string = string[:-1]
      else:
        try:
          string += str (event.unicode)
        except TypeError:
          pass
  surf.fill ((255, )*3)
  surf.blit (font.Font (None, 24).render (string, 1, (0, )*3), (100, 100))
  display.flip ()

Upvotes: 2

Related Questions