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

Pygame中文字被背景图遮挡及AttributeError问题求助

Pygame文字显示问题及AttributeError错误修复

问题描述

我在制作游戏按钮时,想在首页添加更多文字,但文字无法显示在背景图上方——尽管代码里包含flip和update函数。同时出现错误:

AttributeError: type object 'pygame.surface.Surface' has no attribute 'text_surface'

原代码:

pygame.init()
screen = pygame.display.set_mode((1000,800))
clock = pygame.time.Clock()
pygame.display.set_caption('The Chieftain')
test_surface = pygame.image.load('ChieftainGameFolder/Pictures/Game Background/background.PNG').convert_alpha()
tw = test_surface.get_width()
th = test_surface.get_height()
#place elements here, what makes the game run
test_surface2 = pygame.transform.scale(test_surface, (tw * 1.11482720178 ,th * 1.12201963534))

text_font = pygame.font.SysFont("Arial",30)
def draw_text(text, font, text_col, x, y):
    img = font.render(text,True,text_col,)
    screen.blit(img, (x,y))
TEXT_COL = (255,255,255)

#gameloop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    draw_text("Chieftain", text_font, (0,0,0), 500, 400)

    screen.blit(test_surface2,(0,0))
    screen.blit(pygame.surface.Surface.text_surface, (500,400))
    pygame.display.flip()
    pygame.display.update()
    clock.tick(60)

错误原因及修复步骤

  • AttributeError错误:pygame.surface.Surface类本身没有text_surface属性,这行代码属于无意义的错误调用,直接删除即可。
  • 文字被背景覆盖:Pygame的绘制是按顺序叠加的,先绘制的内容会被后绘制的内容覆盖。你原来先画文字,再画背景图,导致文字被挡住,只需调换两者的绘制顺序,先画背景再画文字。
  • 冗余的显示更新:pygame.display.flip()和pygame.display.update()功能重复,保留其中一个即可,推荐用flip()。

修正后的代码

pygame.init()
screen = pygame.display.set_mode((1000,800))
clock = pygame.time.Clock()
pygame.display.set_caption('The Chieftain')
test_surface = pygame.image.load('ChieftainGameFolder/Pictures/Game Background/background.PNG').convert_alpha()
tw = test_surface.get_width()
th = test_surface.get_height()
test_surface2 = pygame.transform.scale(test_surface, (tw * 1.11482720178 ,th * 1.12201963534))

text_font = pygame.font.SysFont("Arial",30)
def draw_text(text, font, text_col, x, y):
    img = font.render(text, True, text_col)
    screen.blit(img, (x,y))
TEXT_COL = (255,255,255)

#gameloop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # 先绘制背景
    screen.blit(test_surface2,(0,0))
    # 再绘制文字,确保文字在背景之上
    draw_text("Chieftain", text_font, (0,0,0), 500, 400)
    
    # 只保留一个显示更新函数
    pygame.display.flip()
    clock.tick(60)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:52:40