A slow but simple way to do it is:
import pygame
def text(surface, fontFace, size, x, y, text, colour):
font = pygame.font.Font(fontFace, size)
text = font.render(text, 1, colour)
surface.blit(text, (x, y))
screen = pygame.display.set_mode(500, 100)
screen.fill((255, 255, 255))
text(screen, 'font.ttf', 32, 5, 5, 'This is text', (0, 0, 0)
But this is slow as you have to load the font every time so I use this:
import pygame
fonts = {}
def text(surface, fontFace, size, x, y, text, colour):
if size in fonts:
font = fonts[size]
else:
font = pygame.font.Font(fontFace, size)
fonts[size] = font
text = font.render(text, 1, colour)
surface.blit(text, (x, y))
screen = pygame.display.set_mode(500, 100)
screen.fill((255, 255, 255))
text(screen, 'font.ttf', 32, 5, 5, 'This is text', (0, 0, 0)
This way, it keeps track of every font size used and if it has already used it, I loads it from a dictionary, otherwise it loads the font and saves it to the dictionary. The only problem is that this only works if you only use one font face, but for different font faces used, you could just have different dictionaries.
To loop just do:
screen = pygame.display.set_mode(500, 100)
running = True
while running:
screen.fill((255, 255, 255))
text(screen, 'font.ttf', 32, 5, 5, 'This is text', (0, 0, 0)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
Also, just a side note, you need a file called 'font.ttf' in the CWD for this example to work.