Pygame - Working with Text

Pygame - Working with Text

In Pygame, working with text involves creating a Font object, rendering the text into an image (Surface), and then blitting this image onto your main screen Surface. Below is a step-by-step guide to display text on the screen in Pygame:

  1. Initialize Pygame: First, you have to initialize Pygame.

    import pygame pygame.init() 
  2. Create the main screen: Set up the main display surface.

    screen = pygame.display.set_mode((640, 480)) 
  3. Create a Font object: You can either use a system font or specify a custom font file.

    • Using a system font:

      font = pygame.font.SysFont('arial', 36) 
    • Using a custom font file:

      font = pygame.font.Font('path/to/font.ttf', 36) 
  4. Render the text: Render the text to create a Surface. The render method takes the text string, a boolean value for antialiasing, and the text color.

    text_surface = font.render('Hello, Pygame!', True, (255, 255, 255)) 
  5. Display the text: Blit the text surface onto the main screen surface at a specified position.

    screen.blit(text_surface, (50, 50)) 
  6. Update the display: To make the rendered text visible on the screen, you need to update the display.

    pygame.display.update() 
  7. Main loop: To keep the window open, you need a main loop that checks for events such as the close button being clicked.

    running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # It's often a good idea to clear the screen each frame before drawing it again. screen.fill((0, 0, 0)) # Redraw the text every frame. screen.blit(text_surface, (50, 50)) pygame.display.update() 
  8. Quit Pygame: After breaking out of the main loop, make sure to quit Pygame properly.

    pygame.quit() 

Here's the complete example put together:

import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('Pygame Text Example') font = pygame.font.SysFont('arial', 36) text_surface = font.render('Hello, Pygame!', True, (255, 255, 255)) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0, 0, 0)) # Fill the screen with black. screen.blit(text_surface, (50, 50)) # Blit the text. pygame.display.update() # Update the full display Surface to the screen. pygame.quit() 

This script initializes Pygame, creates a window, and displays white "Hello, Pygame!" text on a black background. The window will stay open until you close it, and the text will be displayed continuously.


More Tags

command bulma local ta-lib parentheses dart-async gd text-cursor sweetalert2 boot

More Programming Guides

Other Guides

More Programming Examples