Xerath Xerath - 8 months ago 73
Python Question

python library pygame: centering text

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.


You can get the dimensions of the rendered text image using text.get_rect(), which returns a Rect object, which has width and height attributes, among others (see the linked documentation for a full list). I.e. you can cimply do text.get_rect().width.