Pygame - How to Center Text
You can always just center the text rectangle when you grab it:
# draw text
font = pygame.font.Font(None, 25)
text = font.render("You win!", True, BLACK)
text_rect = text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
screen.blit(text, text_rect)
just another option
You can get the dimensions of the rendered text image using text.get_rect()
, which returns a Rect object with width
and height
attributes, among others (see the linked documentation for a full list). I.e. you can simply do text.get_rect().width
.
To simplify the use of text, I use this function (to center it the x is not useful)
import pygame
pygame.init()
WIDTH = HEIGHT = 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.SysFont("Arial", 14)
def write(text, x, y, color="Coral",):
text = font.render(text, 1, pygame.Color(color))
text_rect = text.get_rect(center=(WIDTH//2, y))
return text, text_rect
text, text_rect = write("Hello", 10, 10) # this will be centered anyhow, but at 10 height
loop = 1
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
screen.blit(text, text_rect)
pygame.display.update()
pygame.quit()