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
Active
Viewed 2,133 times
1 Answers
3
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
.

Rabbid76
- 202,892
- 27
- 131
- 174
-
1
-
Do you know how to load a jpg image file in pygame? When I load them it doesn't show in the screen but a png image does. – Debarka Naskar Dec 30 '21 at 10:36
-
@DebarkaNaskar jpg can be loaded the same way as png with [`pygame.image.load`](https://www.pygame.org/docs/ref/image.html#pygame.image.load). Make sure the image path and file extension is correct. If you're using Windows, make sure the name of the image isn't something like "name.jpg.jgp". Note that the file extension is hidden in Explorer by default. – Rabbid76 Dec 30 '21 at 10:38
-
1Thanks again! I noticed that I made a typo and when I fixed it all worked fine. – Debarka Naskar Dec 30 '21 at 11:09
-
This is beautiful, thank you! I used to think we had to manually subtract `centerx` and `centery`, now I know that we don't! – Arthur Khazbs Nov 01 '22 at 22:25