How to Center Text in Pygame

pygame, python, python-3.x

Solution

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`.

Problem

I have some 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 the text's width and height, so I can center text like this: ``` 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.

Original source