How to display text in pygame?

user3146817 picture user3146817 · Dec 30, 2013 · Viewed 123.2k times · Source

I can't figure out to display text in pygame.
I know I can't use print like in regular python IDLE but i dont know how

import pygame, sys
from pygame.locals import *

BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)

pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)

DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:           
            pygame.display.update() 

import time

direction = ''
print('Welcome to Earth')
pygame.draw.rect(screen, RED, [55,500,10,5], 0)
time.sleep(1)

THIS is only the beginning part of the whole program.
If there is a format that will allow me to show the text I type in the pygame window that'd be great. So instead of using print I would use something else. But i don't know what that something else is :/ When I run my program in pygame it doesnt show anything.
I want the program to run in the pygame window instead of it just running in idle.

Answer

Bartlomiej Lewandowski picture Bartlomiej Lewandowski · Dec 30, 2013

You can create a surface with text on it. For this take a look at this short example:

pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)

This creates a new object on which you can call the render method.

textsurface = myfont.render('Some Text', False, (0, 0, 0))

This creates a new surface with text already drawn onto it. At the end you can just blit the text surface onto your main screen.

screen.blit(textsurface,(0,0))

Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.