python library pygame: centering text

Xerath picture Xerath · Jun 1, 2014 · Viewed 19.7k times · Source

I have a code:

# draw text
font = pygame.font.Font(None, 25)
text = font.render("You win!", True, BLACK)
screen.blit(text, [SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2])

How can I get text width and height methods like in java, so I can center text like:

screen.blit(text, [SCREEN_WIDTH / 2 - text_w / 2, SCREEN_HEIGHT / 2 - text_h / 2])

If this is not possible, what is another way ? I've found this example, but I didn't really understand it.

Answer

The4thIceman picture The4thIceman · Sep 19, 2016

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