使用pygam从.zip加载文件时,“文件路径包含空字符”

2024-06-17 15:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个游戏,其中包括图像,文本和音频文件位于一个密码保护.zip。我正在尝试使用pygame.image.load并显示如下图像:

from zipfile import ZipFile
import pygame
import pyganim
import sys

pygame.init()
root = pygame.display.set_mode((320, 240), 0, 32)
pygame.display.set_caption('image load test')



archive = ZipFile("spam.zip", 'r')
mcimg = archive.read("a.png", pwd=b'onlyforthedev')

mc = pygame.image.load(mcimg)

anime = pyganim.PygAnimation([(mcimg, 100),
                              (mcimg, 100)])
anime.play()

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


    windowSurface.fill((100, 50, 50))
    anime.blit(root, (100, 50))
    pygame.display.update()

这是我从中得到的错误:

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\VERY IMPORTANT FOR GAME DISTRIBUTION\few.py", 
  line 41, in <module>
  mc = pygame.image.load(mcimg)
  pygame.error: File path '�PNG


  ' contains null characters

Tags: 图像imageimporteventdisplaysysloadroot
1条回答
网友
1楼 · 发布于 2024-06-17 15:42:11

函数^{}可以从文件源加载图像。可以传递文件名或类似对象的Python文件。你知道吗

但是,实际上你给了图像字节。你知道吗

要解决此问题,可以将字节包装到io.Bytes实例中,并将其用作类似文件的对象:

import zipfile
import io

with zipfile.ZipFile("spam.zip", 'r') as archive:
    mcimg = archive.read("a.png", pwd=b'onlyforthedev')

mc = pygame.image.load(io.BytesIO(mcimg))

相关问题 更多 >