How to center an image in the middle of the window in pygame?

Question:

So I am Loading an Image in python and I need to Center the Image in Pygame. As Pygame starts the drawing from the upper left side of the screen so the x and y coordinates 0,0 doesn’t work. Can anyone tell me the center x and y coordinates of the pygame window?

Asked By: Debarka Naskar

||

Answers:

You can get the center of the window through the window rectangle (pygame.Surface.get_rect):

screen = pygame.display.set_mode((800, 600))
center = screen.get_rect().center

Use this to blit an image (pygame.Surface object) in the center of the screen:

screen.blit(image, image.get_rect(center = screen.get_rect().center))

pygame.Surface.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0). However, the position of the rectangle can be specified with a keyword argument. In this case, the center of the rectangle is set by the center of the screen.
When the 2nd argument of blit is a rectangle (pygame.Rect), the upper left corner of the rectangle will be used as the position for the blit.

Answered By: Rabbid76
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.