Real Time Typing In Pygame
I am trying to write a small piggybank program. I already have a window with some background and text but I need to add a functionality for the user to let him add money to the pig
Solution 1:
Here is a short example:
#creates a newstring, that will store the character you have written
number_str = ""
#create a new Font object that is used to render the stringinto a Surface object
font_renderer = pygame.font.Font("monospace", 15)
whileTrue:
screen.fill((0,0,0)) # fill the whole screen with a black color
# create a new Surface objectfrom a string, where the textis white.
rendered_number = font_renderer.render(number_str, True, (255,255,255))
#draws the created Surface onto the screen at position 100,100
screen.blit(rendered_number, (100, 100))
# updates the screen to show changes
pygame.display.flip()
foreventin pygame.event.get():
ifevent.type == pygame.KEYDOWN:
if pygame.KEY_0 < event.key < pygame.KEY_9: # checks the key pressed
character = chr(event.key) #converts the number to a character
number_str += str(character) #adds the number to the endof the string
Solution 2:
You might want to do something like what's explained in this tutorial:
"""Edit text with the keyboard."""
import pygame
from pygame.locals import *
import time
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GRAY = (200, 200, 200)
pygame.init()
screen = pygame.display.set_mode((640, 240))
text = 'this text is editable'
font = pygame.font.SysFont(None, 48)
img = font.render(text, True, RED)
rect = img.get_rect()
rect.topleft = (20, 20)
cursor = Rect(rect.topright, (3, rect.height))
running = True
background = GRAY
while running:
foreventin pygame.event.get():
ifevent.type == QUIT:
running = Falseifevent.type == KEYDOWN:
ifevent.key == K_BACKSPACE:
if len(text)>0:
text = text[:-1]
else:
text += event.unicode
img = font.render(text, True, RED)
rect.size=img.get_size()
cursor.topleft = rect.topright
screen.fill(background)
screen.blit(img, rect)
if time.time() % 1 > 0.5:
pygame.draw.rect(screen, RED, cursor)
pygame.display.update()
pygame.quit()
Post a Comment for "Real Time Typing In Pygame"