本文介绍了错误 - pygame.error: 无法打开 backround.png.使固定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to load an image into a window on pygame but when i run the code. It pops up with an error of

pygame.error: 无法打开 backround.png

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

I have the image in the same folder with the code itself. I have done this for another script and it works perfectly fine. I am not sure what the problem is.

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

I've tried closing my program. Renaming the file but that's about it. Not sure how to tackle the problem. Any help is much appreciated

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()

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

Like I said: I have used similar layout to load images with another file and it works perfectly fine but for some reason it doesn't load the image in case.

推荐答案

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

The image filepath has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.

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

The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd().

如果图片和python文件在同一个文件夹,那么你cnb获取文件的目录并通过os.chdir(path):

If the image is in the same folder as the python file, then you cnb get the directory of the file and change the working directory by 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连接图片文件名和文件路径.例如:

or concatenate the image filename and the file path by os.path.join. e.g.:

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'))

这篇关于错误 - pygame.error: 无法打开 backround.png.使固定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:55