You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame按钮点击后Loop函数失效,游戏画面未正常加载(附代码)

问题分析与解决方案

我看了你的代码,发现两个关键问题导致按下按钮后预期图像不显示、菜单元素仍停留在界面上:

1. 游戏场景图片位置完全超出屏幕范围

在In_Game函数里,你设置了:

x=900
y=600
In_Game_Earth_Image(x,y)

你的游戏窗口是900x600尺寸,这意味着图片的左上角坐标是(900,600)——刚好落在屏幕的右下角外侧,自然看不到任何图像。你需要把x和y改成0,让图片从屏幕左上角开始绘制:

x=0
y=0
In_Game_Earth_Image(x,y)

2. 菜单循环中的更新逻辑混乱

你的button函数里每次都会调用pygame.display.update(),而Menu循环本身也会调用一次pygame.display.update(),这种重复更新会导致界面渲染不连贯,切换到游戏场景时,之前的菜单元素可能残存在缓冲区里。

解决方法是移除button函数里的pygame.display.update(),只在Menu循环的最后统一执行一次界面更新。修改后的button函数片段:

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click=pygame.mouse.get_pressed()
    if x+w > mouse[0] > x and y +h > mouse[1] > y:
        pygame.draw.rect(gameDisplay, ac,(x, y, w, h) )
        if click[0]==1 and action != None:
            if action=="Start":
                In_Game()
            elif action=="quit":
                pygame.quit()
                quit()
    else:
        pygame.draw.rect(gameDisplay, ic,(x, y, w, h) )
    smallText=pygame.font.Font("freesansbold.ttf", 20)
    textSurf, textRect=text_objects(msg, smallText)
    textRect.center=( (x+(w/2)), (y+(h/2)))
    gameDisplay.blit(textSurf, textRect)
    # 移除此处的pygame.display.update()

另外,建议在In_Game循环里确保每次都先绘制游戏背景,彻底覆盖之前的菜单元素。修改后的In_Game函数:

def In_Game():
    x=0
    y=0
    gameExit=False
    while not gameExit:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                quit()
        # 每次循环都绘制游戏背景图片
        In_Game_Earth_Image(x,y)
        pygame.display.update()
        clock.tick(60)

把这些修改应用到你的代码中,按下Play按钮后就能正常显示游戏场景的图片了。

内容的提问来源于stack exchange,提问作者Dawid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:52:38