How do I only center text on x-axis, but be able to move the y-axis in pygame?

Viewed 367

I am trying to put text in the center of the screen, but also on top to label the text in the center. In order to center the text currently, I am using the code below...

info = pygame.display.Info()
screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.FULLSCREEN)
screen_rect = screen.get_rect()

txt = font.render("some random message", True, color)

screen.blit(txt, txt.get_rect(center=screen_rect.center))

But I cannot find a way to modify the center using get_rect() to edit just the y-axis. I also could not find any more elaboration about the get_rect() function in the documentation.

1 Answers

The pygame.Rect object has the following attributes:

x, y 
top, left, bottom, right 
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery 
size, width, height
w,h

So you could set the centerx to the screen's centerx to make the rectangle centered without affecting the y value.

screen.blit(text, text.get_rect(centerx=screen_rect.centerx))

For completion, if you want it centered at the top, you could write

screen.blit(text, text.get_rect(midtop=screen_rect.midtop)

and centered at the bottom

screen.blit(text, text.get_rect(midbottom=screen_rect.midbottom)
Related