Centring text in a rect in PyGame?

Tim Golden mail at timgolden.me.uk
Sun Dec 8 10:42:44 EST 2013


On 07/12/2013 12:41, Eamonn Rea wrote:
> Anyway, I have a problem. In my game, I want to draw a button. I’ve
> gotten the button to draw fine, but I want some text on the button. I’ve
> gotten the text to draw, but I can’t get it to centre into the button.
> Here’s the code I’ve used:
>
> *self.surface.blit(self.button_text, (self.width / 2 -
> self.button_text.get_width() / 2, self.height / 2 -
> self.button_text.get_height() / 2))*

Side-stepping your actual code, here's a handy thing in pygame. You can 
center one rect on another to achieve the same effect without bothering 
with the (x - y) / 2 stuff.

import pygame
pygame.init()

#
# For demo purposes, the button is the whole window
#

button = pygame.display.set_mode((400, 320))

#
# Create 12-point text in white saying "Hello, World!"
#
font = pygame.font.Font(pygame.font.get_default_font(), 12)
text = font.render("Hello, World!", True, (0xff, 0xff, 0xff))

#
# Use the text's rect to get width / height
# Then center that rect on the target surface
#
text_rect = text.get_rect()
text_rect.center = button.get_rect().center
button.blit(text, text_rect)

pygame.display.flip()



TJG



More information about the Python-list mailing list