Python - Display text to PyGame window


Pygame is a multimedia library for Python for making games and multimedia applications. In this article we will see how to use the pygame module to get customized font and text on the screen taking into consideration, its height, width, and position in the pygame window.

In the below program we initialize the pygame module and then define the mode and the caption for the image. Next we add the font text and define the coordinates for the font. The screen.blit function paints the screen while the while loop keeps listening the end of the game is clicked.

Example

import pygame
import sys
# Initialize pygame
pygame.init()
#scren dimension
sur_obj=pygame.display.set_mode((300,200))
# Screen caption
pygame.display.set_caption("Text in Pygame")
font_color=(0,150,250)
font_obj=pygame.font.Font("C:\Windows\Fonts\segoeprb.ttf",25)
# Render the objects
text_obj=font_obj.render("Welcome to Pygame",True,font_color)
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

Running the above code gives us the following result −

Updated on: 25-Jan-2021

682 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements