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

Pygame调用blit绘制图像报错:参数需为pygame.Surface而非函数

问题原因

你的代码出现了标识符命名冲突:
你首先用player作为变量名存储了加载得到的Pygame Surface(玩家图片对象),后续又定义了同名的player()函数。Python中后定义的同名标识符会覆盖之前的定义,因此你在函数内调用screen.blit(player, (playerX, playerY))时,此时的player已经是函数对象,而非预期的Surface对象,触发类型错误。

修复方案

二选一即可:

  • 修改函数名,避免与图片变量重名,比如将绘制函数改名为draw_player,同时同步修改主循环里的函数调用语句
  • 修改图片变量名,避免与函数重名,比如将存储玩家图片的变量改名为player_img,同时同步修改blit方法的第一个参数

修正后的参考代码

import pygame

#Initialize pygame module
pygame.init()

#Create Screen
screen = pygame.display.set_mode((1000, 600))

#Title and Icon
pygame.display.set_caption("Jungle Invader")
icon = pygame.image.load('fox-sitting.png')
pygame.display.set_icon(icon)

# Player
player_img = pygame.image.load('cat.png')
playerX = 300
playerY = 500

def draw_player():
    screen.blit(player_img, (playerX, playerY))


#Main loop
running = True
while running:
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((244, 232, 255))
    draw_player()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:06:03