Display Text in pygame Window using Python

In this module, we are going to learn how to display text on the pygame window using Python.

Display Text Using pygame.font.Font() in Python

Displaying Text on the pygame window can be done by using the following syntax

font_obj=pygame.font.Font("Font Type",Font_Size)

Here, font_obj that stores the type of font that we want to use in our code and it’s size. There are different fonts like freesansbold, times new roman, Arial, etc and this is implemented with the extension of ttf.

To get the fonts present in your system use the following syntax

pygame.font.get_fonts()

This function returns a list that contains all the fonts in your system.

Now let us implement the font our pygame window as follows

import pygame
import sys
pygame.init()
sur_obj=pygame.display.set_mode((300,200))
pygame.display.set_caption("Font Explanation")
Green=(0,255,0)
font_obj=pygame.font.Font("C:\Windows\Fonts\Arial.ttf",25) 
text_obj=font_obj.render("This is Text",True,Green) 
while True: 
      sur_obj.fill((255,255,255)) 
      sur_obj.blit(text_obj,(22,0)) 
      for eve in pygame.event.get(): 
         if eve.type==pygame.QUIT: 
                 pygame.quit() 
                 sys.exit() 
      pygame.display.update()

Output:

Display Text in pygame Window using Python

Here we get the output as “This is Text ” is printed on to screen with green color.

font_obj=pygame.font.Font("C:\Windows\Fonts\georgia.ttf",25)
text_obj=font_obj.render("This is Text",True,Green)

These two statements are the core part of this code here font_obj determines the type of font that we want to use here, as we can see I used an Arial font that is present in c drive I have copied the location. The font should always be in a .ttf format ttf indicates true type font file. text_obj is used to apply the font we have chosen to our text takes the message that we want to display and antialias is True, color for text can also be specified in this area here it is green and background color is none.

The syntax for rendering is as follows

text_obj=font_obj.render(text, antialias, color, background=None)

After completing these tasks we add text to screen using pygame.blit()

sur_obj.blit(text_obj,(22,0))

The text is placed at a position(22,0).

Also read:

Play Video in Python Using Pygame

Leave a Reply