Pygame按钮类生成新窗口而非原窗口显示问题求助
问题原因分析
- 第一个独立的
while (status)循环独占窗口资源,仅处理关闭事件,必须等用户关闭窗口后才会执行后续的按钮创建、主游戏循环代码,因此出现先显示纯背景窗口,关闭后才进入带按钮的窗口的现象。 - 主游戏循环中的
screen.fill((20, 20, 20))会完全覆盖之前绘制的背景图,导致背景无法在按钮界面中保留。
修复步骤
- 删除第一个多余的
while (status)循环,将背景绘制逻辑迁移到主游戏循环内。 - 主循环中优先绘制背景图,再处理按钮渲染,避免背景被填充色覆盖。
- 修正按钮实例创建时的重复赋值问题(原代码三次赋值给同一变量,虽不影响
objects列表,但不符合代码规范)。
修复后的完整代码
# import the pygame module import pygame import sys pygame.init() width, height =1550,800 fps = 60 fpsClock = pygame.time.Clock() screen=pygame.display.set_mode((width, height)) font=pygame.font.SysFont('arial',40) objects = [] pygame.display.set_caption('image') # 统一路径斜杠,避免解析错误 imp=pygame.image.load("D:/PycharmProjects/flay high bangtan/flappy bird/sprites/background/main page.jpg") #COMMAND BUTTONS class Button(): def __init__(self, x, y, width, height, buttonText='Button', onclickFunction=None, onePress=False): self.x = x self.y = y self.width = width self.height = height self.onclickFunction = onclickFunction self.onePress = onePress self.fillColors = { 'normal': '#ffffff', 'hover': '#666666', 'pressed': '#333333', } self.buttonSurface = pygame.Surface((self.width, self.height)) self.buttonRect = pygame.Rect(self.x, self.y, self.width, self.height) self.buttonSurf = font.render(buttonText, True, (20, 20, 20)) self.alreadyPressed = False objects.append(self) def process(self): mousePos = pygame.mouse.get_pos() self.buttonSurface.fill(self.fillColors['normal']) if self.buttonRect.collidepoint(mousePos): self.buttonSurface.fill(self.fillColors['hover']) if pygame.mouse.get_pressed(num_buttons=3)[0]: self.buttonSurface.fill(self.fillColors['pressed']) if self.onePress: self.onclickFunction() elif not self.alreadyPressed: self.onclickFunction() self.alreadyPressed = True else: self.alreadyPressed = False self.buttonSurface.blit(self.buttonSurf, [ self.buttonRect.width / 2 - self.buttonSurf.get_rect().width / 2, self.buttonRect.height / 2 - self.buttonSurf.get_rect().height / 2 ]) screen.blit(self.buttonSurface, self.buttonRect) def myFunction(): print('Button Pressed') # 创建按钮,避免重复赋值 Button(30, 30, 400, 100, 'PLAY', myFunction) Button(30, 140, 400, 100, 'ABOUT US', myFunction) Button(30, 250, 400, 100, 'EXIT', myFunction) # 主游戏循环 while True: # 先绘制背景图 screen.blit(imp,(0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for obj in objects: obj.process() pygame.display.flip() fpsClock.tick(fps)
额外提示
- 路径规范:Windows系统中建议统一使用
/或双重反斜杠\\作为路径分隔符,避免因混用斜杠导致的图片加载失败。 - 按钮实例:若后续需要单独操作某个按钮,可给每个按钮分配独立变量名(如
play_btn、about_btn),方便维护。
内容的提问来源于stack exchange,提问作者chetana
相关产品推荐
相关产品推荐

