Search code examples
pythonpython-3.xmacospygamemacos-monterey

How to use custom fonts in pygame?


Specs: MacOS Monterey, Python 3.10.4, Pygame 2.1.2

Context: I'm trying to create a game using the Pygame module in Python. I want to display text on the screen and have figured that part out. What I'm not sure about is if I'm able to use custom fonts. By custom fonts I mean I've downloaded a font in the form of a .ttf file.

Question: Is there any way to use this .ttf file/font in Pygame? I understand there are some built-in fonts like Comic Sans.


Solution

  • You can use a custom font with the following code:

    font = pygame.font.Font(<font file>, <size>)
    

    then render it using

    font.render(<text>, True, <colour>)
    

    See also https://nerdparadise.com/programming/pygame/part5 and https://www.pygame.org/docs/ref/font.html