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

Python使用Pygame创建图像显示函数时遇TypeError问题求助

Pygame类调用方法报错:'pygame.Surface' object is not callable

问题代码

import pygame

white = (255,255,255)
width,height = 800,500
win = pygame.display.set_mode((width,height))
pygame.display.set_caption("Test")

class Game:
    def __init__(self):
        self.player = pygame.image.load("graphics/player/player.png")
    def player(self):
        win.blit(self.player, (0,0))
        pygame.display.update()
    
    
game = Game()

def functions():
    game.player()

def loop():
    flag = True
    clock = pygame.time.Clock()

    while flag:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                flag = False
                pygame.quit()

        functions()
        pygame.display.update()


loop()

报错信息

Traceback (most recent call last):
  File "C:", line 35, in <module>
    loop()
  File "C:", line 32, in loop
    functions()
  File "C:", line 19, in functions
    game.player()
TypeError: 'pygame.Surface' object is not callable

解决方法

核心问题是类的实例属性和方法同名冲突:

  • 在Game类的__init__方法中,self.player被赋值为pygame.image.load返回的Surface对象;
  • 同时你定义了名为player的方法,这会导致方法被实例属性覆盖。当调用game.player()时,实际是在尝试调用那个Surface对象,而它不是可调用的函数,因此触发报错。

只需要把方法名改成和属性名不同的名称即可,比如改为draw_player:

修改后的关键代码:

class Game:
    def __init__(self):
        self.player = pygame.image.load("graphics/player/player.png")
    def draw_player(self):
        win.blit(self.player, (0,0))

# 同步修改调用逻辑
def functions():
    game.draw_player()

额外优化建议:

  • 不要在方法内重复调用pygame.display.update(),主循环末尾已经有一次刷新操作,重复调用会浪费性能;
  • 触发退出事件时,在pygame.quit()后建议添加import sys; sys.exit(),避免Pygame退出后代码继续执行引发其他错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:01:00