pygame.Surface.get_rect.get_rect()
returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument. For example, the center of the rectangle can be specified with the keyword argument center
. These keyword argument are applied to the attributes of the pygame.Rect
before it is returned (see pygame.Rect
for a full list of the keyword arguments).
Get the text rectangle and place the center of the text rectangle on the center of the window rectangle:
text_rect = text.get_rect(center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
You can even get the center of the window from the display Surface :
text_rect = text.get_rect(center = screen.get_rect().center)
Or with the use of pygame.display.get_surface()
:
text_rect = text.get_rect(center = pygame.display.get_surface().get_rect().center)
A Surface can be drawn on another Surface using the blit
method. The second argument is either a tuple (x, y) representing the upper left corner or a rectangle. With a rectangle, only the upper left corner of the rectangle is taken into account. Therefore you can pass the text rectangle directly to blit
:
screen.blit(text, text_rect)
Minimal example:

import pygame
import pygame.font
pygame.init()
font = pygame.font.SysFont(None, 50)
text = font.render('Hello World', True, (255, 0, 0))
window = pygame.display.set_mode((300, 100))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()