In this Pygame Tutorial we want to talk about Working with Fonts in Pygame, so Pygame is popular Python library and it is used for building games and graphical applications. when you are building game or application than you need to choose the right font, in this article we want to learn about loading the font in pygame.
How to Work with Fonts in Pygame
First of all we need to install Pygame library, and you can use pip for that.
1 |
pip install pygame |
This is the complete code for this article, make sure that you have downloaded a font
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import pygame pygame.init() # Load font from file font = pygame.font.Font('font.ttf', 36) # Render text text_surface = font.render('Codeloop.org', True, (255, 255, 255)) # Create display screen = pygame.display.set_mode((800, 600)) # Blit text to the display screen.blit(text_surface, (300, 250)) # Update the display pygame.display.update() # Main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() |
So in the above code first of all we need to import and initialize pygame.
1 2 |
import pygame pygame.init() |
After that we can load a font file that we want to use in our game or application. Pygame provides a font module that allows us to load fonts from files on our computer. this is is an example of how to load a font:
1 |
font = pygame.font.Font('font.ttf', 36) |
Now that we have loaded our font, we can use it to render text on the display. Pygame provides render function in the font module that allows us to create a new surface object that contains the rendered text. this is an example of how to render text using our loaded font.
1 |
text_surface = font.render('codeloop.org', True, (255, 255, 255)) |
And lastly, we can blit our rendered text to the display. Pygame provides blit function that allows us to draw our Surface object onto the display. this is an example of how to blit our text to the display.
1 2 3 |
screen = pygame.display.set_mode((800, 600)) screen.blit(text_surface, (300, 250)) pygame.display.update() |
PyGame Tutorial – Add Sound Effects to Pygame
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email