Home | GitHub | Pygame Docs
In this article, we'll learn how to use custom and system fonts in Pygame.
Before using fonts in pygame, keep in mind that you have to initialize pygame before using the pygame.font
module. To do that, you can simply put pygame.init()
or pygame.font.init()
at the top of your python script.
pygame.font.SysFont
class:pygame.font.SysFont(name, size, bold=False, italic=False) -> Font
"comicsans"
), and the second being the size of the font (as an integer).bold
and italic
parameters (they are booleans), which are False
by default.
font = pygame.font.SysFont("comicsans", 32, bold=True)
pygame.font.Font
class:Font(filename, size) -> Font
Font(pathlib.Path, size) -> Font
Font(object, size) -> Font
"my_font.ttf"
), and the second being the size of the font (as an integer).
font = pygame.font.Font("arima.ttf", 32)
pygame.font.Font
. To do this, you can use None
as the font
argument, for example:font = pygame.font.Font(None, 32)
To render a pygame.font.Font
object, we can use the pygame.font.Font.render
method:
render(text, antialias, color, background=None) -> Surface
text
, which is a string with the text you want to render;antialias
, which is a boolean indicating whether you want your text to have smooth edges;color
, which is usually a tuple[int, int, int]
or a string;background
, which is usually a tuple[int, int, int]
or a string.pygame.Surface
. Here's some docs from the pygame documentation: "This creates a new Surface with the specified text rendered on it. pygame provides no way to directly draw text on an existing Surface: instead you must use Font.render() to create an image (Surface) of the text, then blit this image onto another Surface. The text can only be a single line: newline characters are not rendered."
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 450))
clock = pygame.time.Clock()
# None for the default font
font = pygame.font.Font(None, 64)
# here we are rendering text that says "Test"
font_surface = font.render("Test", True, "white")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill("black")
# draw the text
screen.blit(font_surface, (0, 0))
clock.tick(30)
pygame.display.flip()
pygame.quit()