【问题标题】:Error - pygame.error: Couldn't open backround.png. Fix? [duplicate]错误 - pygame.error: 无法打开 backround.png。使固定? [复制]
【发布时间】:2019-09-07 18:41:52
【问题描述】:

我试图将图像加载到 pygame 的窗口中,但是当我运行代码时。它弹出一个错误

pygame.error: 无法打开 backround.png

我将图像与代码本身放在同一个文件夹中。我已经为另一个脚本做了这个,它工作得很好。我不确定是什么问题。

我已经尝试关闭我的程序。重命名文件,仅此而已。不知道如何解决这个问题。非常感谢任何帮助

import pygame
import os
from Introduction import *

# Making the window
pygame.init()
windowSize = (800, 600)
screen = pygame.display.set_mode(windowSize)

# Images in the Introduction
GameBackround = pygame.image.load('backround.png')

while True:

    screen.blit(GameBackround, (0,0))

    for event in pygame.event.get():

        screen.blit(GameBackround, (0,0))

    pygame.display.update()
    pygame.display.flip()

就像我说的:我使用类似的布局来加载另一个文件的图像,它工作得非常好,但由于某种原因它不会加载图像以防万一。

【问题讨论】:

  • 我认为这不是问题,因为它在您的代码中是一致的,但您拼错了“背景”

标签: python python-3.x pygame


【解决方案1】:

图像文件路径必须相对于当前工作目录。工作目录可能与python文件所在目录不同。

文件名和路径可以通过__file__获取。当前工作目录可以通过os.getcwd()获取。

如果图片和python文件在同一个文件夹,那么你cnb获取文件的目录,把工作目录改成os.chdir(path):

import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir )

或通过os.path.join 连接图像文件名和文件路径。例如:

import pygame
import os
from Introduction import *

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

GameBackround = pygame.image.load(os.path.join(sourceFileDir, 'backround.png'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2019-05-02
    • 2015-04-30
    • 2014-06-18
    • 2012-04-16
    • 2011-04-17
    相关资源
    最近更新 更多