调整pygame窗口大小后如何调整按钮的大小?

时间:2020-10-06 16:49:14

标签: python pygame

我有一个菜单(main_menu),它具有一个Button,并且我希望在调整窗口大小后此按钮保留在中间。该程序确实在窗口中间绘制了一个新按钮,但是旧按钮仍然可见,我无法弄清楚原因。我尝试再次用背景色填充屏幕,然后绘制一个新按钮,但是旧按钮仍然可见...有任何想法吗?

enter image description here enter image description here

WINDOW_W , WINDOW_H =  1200, 800
SCREEN = pg.display.set_mode((WINDOW_W,WINDOW_H),pg.RESIZABLE)
main_menu = Main_Menu(SCREEN)
main_menu.render()

while True:
    pg.event.pump()
    event = pg.event.wait()

    if event.type == pg.VIDEORESIZE:    
        new_w, new_h = event.dict['size']   
        SCREEN = pg.display.set_mode((new_w, new_h), pg.RESIZABLE)        
        main_menu = Main_Menu(SCREEN)
        main_menu.render()


class Main_Menu:

    def __init__(self, screen):
        self.screen = screen
        screen_width, screen_height = screen.get_size()
        play_button = Button((255,0,0), screen_width/2 - 100, screen_height/2 - 25, 200, 50, "Test")
        self.button = play_button

    def render(self):

        self.button.draw(self.screen, 1) 
        pg.display.update()




class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self,win,outline=None):
        #Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
            
        pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
        
        if self.text != '':
            font = pygame.font.SysFont('comicsans', 60)
            text = font.render(self.text, 1, (0,0,0))
            win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

2 个答案:

答案 0 :(得分:0)

您想要保存按钮尺寸和屏幕尺寸之间的原始比例。 之后,您要检查循环,然后更改屏幕大小。 如果是这样,请将按钮的大小改回相同的比例。

与按钮的位置相同,只需确保比率一致即可。

答案 1 :(得分:0)

这是一个最小的示例,该示例绘制的图像在调整窗口大小时停留在窗口的中央:

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:
    for event in pygame.event.get():
        if event.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()

如果您使用的是pygame 2的开发版本,则无需通过调用screen重新创建pygame.display.set_mode(…)