Skip to content Skip to sidebar Skip to footer

How To Resize Button After Resizing Pygame Window?

I have a menu (main_menu), that has a Button and I want this button to stay in the middle after I resize the window. The program does draw a new button in the middle of the window

Solution 1:

You would want to save the original ratio between the size of the button and the size of the screen. After that you want to check in a loop wether the screen size changed. If so, change the size of the button back to the same ratio.

And same with the position of the button, just make sure that the ratio is consistent.

Solution 2:

Here's a minimal example drawing an image that stays in the centre of the window as the window is resized:

import pygame

pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
image = pygame.Surface((120, 100), pygame.SRCALPHA)
image.fill(pygame.color.Color("royalblue"))
center_pos = (width // 2, height // 2)while True:
    foreventin pygame.event.get():
        ifevent.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.VIDEORESIZE:
            width, height = event.dict["size"]
            # recreate screen object required for pygame version 1
            screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
            # TODO: resize image if needed
            center_pos = (width // 2, height // 2)
    screen.fill(0)
    screen.blit(image, image.get_rect(center=center_pos))
    pygame.display.update()

If you're using the development release of pygame 2 then you won't need to recreate screen by calling pygame.display.set_mode(…).

Post a Comment for "How To Resize Button After Resizing Pygame Window?"