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

Pygame加载列表中卡牌图片失败:类型错误(需Surface而非JpegImageFile)

Pygame卡牌绘制TypeError问题解决方法

核心问题原因

你用Image.open()是PIL库的方法,返回的是PIL的JpegImageFile对象,而Pygame的screen.blit()只接受Pygame Surface对象,这就是报错的根本原因。

正确的图片加载方式

直接用Pygame自带的pygame.image.load()加载图片,它会直接返回符合要求的Surface对象。示例代码:

import pygame
import glob

pygame.init()
screen = pygame.display.set_mode((800, 600))

# 遍历Cards目录下的jpg文件,用pygame.image.load加载
card_list = []
for img_path in glob.glob("Cards/*.jpg"):
    # 用convert()优化显示性能,若图片带透明通道改用convert_alpha()
    card_surface = pygame.image.load(img_path).convert()
    card_list.append(card_surface)

排查pygame.image.load()无效的可能原因

  • 路径问题:打印img_path确认路径是否正确,注意相对路径的基准是你的代码运行目录,Windows和Linux/macOS的路径分隔符、文件名大小写规则有差异。
  • 图片格式兼容:部分jpg文件可能存在编码问题,尝试用convert()或convert_alpha()处理加载后的Surface,统一颜色格式。
  • 列表赋值错误:打印type(card_list[0])确认元素类型是否为<class 'pygame.Surface'>,排查是否有代码仍在往列表里存入PIL对象。

点击按钮绘制的示例代码

import random

# 假设cards_button是你定义的按钮碰撞区域
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            if cards_button.collidepoint(mouse_pos):
                if card_list:
                    random_card = random.choice(card_list)
                    screen.blit(random_card, (100, 100))  # 按需求调整绘制位置
                    pygame.display.flip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:30:44