Error - pygame.error: Couldn't open backround.png. Fix? [duplicate] - python

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
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: Couldn't open 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.

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.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd().
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 )
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'))

Related

How to add icon into toolbar QAction [duplicate]

I'm currently using QT designer to show a picture on my loading screen.
It should look like this:
However, it looks like this:
This is because for some reason its not showing my picture, when it registers in my IDE that the filepath is correct as seen here:
The only time the picture actually shows in my loading GUI is when I use the FULL file path which is: C:\Users\myalt\OneDrive\Desktop\GUINEW\assets\PostmonkeyLogo.png
But of course, this is not viable when this software will be used on many different computer with different file paths.
self.label.setPixmap(QPixmap(u"assets/PostmonkeyLogo.png")) ## image file path to show
The problem is that the file path is relative to where the console was opened and the python.exe command is executed. It is better to build the full path using the information as the path of the .py:
import os.path
# ...
CURRENT_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(CURRENT_DIRECTORY, "assets/PostmonkeyLogo.png")
self.label.setPixmap(QPixmap(filename))

Why does it says that couldn't open shooting_game\player.png on Pygame? [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
Why does it says that couldn't open shooting_game\player.png on Pygame?
Here's my code so far:
import pygame
import os
width, height = 500, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shooter Game")
player = pygame.image.load(os.path.join("shooter_game", "player.png"))
This gives me a error:
Exception has occurred: error
Couldn't open shooter_game/player.png
File "C:\python_games\shooter_game\game.py", line 11, in <module>
player = pygame.image.load(os.path.join("shooter_game", "player.png"))
I maked sure that player.png's folder was
in the same folder as game.py's folder.
Can someone help me figure out this problem?
Thanks.
If player.png is in the same folder as game.py, you should look for it in the shooter_game directory:
player = pygame.image.load("player.png")
Relative paths are based on current working directory, not the script's directory. If you happen to have changed to the script's directory to run it, they are both the same and it works by shear luck. Otherwise you'll get this error. Python scripts have a __file__ variable holding the script's file name. You can leverage that to find the directory.
player = pygame.image.load(os.path.join(
os.path.dirname(os.path.abspath(__file__))),
"player.png")
pathlib has an alternate way of handling file system paths
from pathlib import Path
player = pygame.image.load(Path(__file__).absolute().parent/"player.png")

I'm not being able to open images in PyCharm editor to add to my program (MacBook)

I'm not able to add in images to my programme in Pycharm, I've imported Pygame and os and it wouldn't work. The image is in .png format 64 bit from flaticon.com
Is there something else I need to do to be able to add it in, I was following a PyGame tutorial online since I'm a beginner in programming
The python launcher just glitches when I add anything to do with an image. everything else works perfectly fine.
Here is the entire code of the project so far:
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Space Invaders - GAME ONE (PyGame)")
playerImg = pygame.image.load('space-invaders.png')
playerX = 370
playerY = 480
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
pygame.display.update()
this is the error message:
playerImg = pygame.image.load('space-invaders.png')
pygame.error: Couldn't open space-invaders.png
Process finished with exit code 1
it just glitches with any addition of an image. If I remove all image related code, it works fine
Also, import os just greys out in the editor
First check if the image is in the same folder as your .py. Next, make sure the image is really .png not just renamed for example, check this by trying to load another image. Last but not the least, check the spelling, maybe the name of the picture is misspelled. Since you are not using paths I can't remember anything else that could cause the issue.
Also, I do not know if it is the mistake during the copy process but last 2 lines of code need to be inside the for loop. And why you have imported os?
EDIT: Answer to the OP question in the comment
By importing os you can now use this module, nothing more. Here is how you can locate your .png file:
current_dir = os.path.dirname(__file__) #The location of your `.py`
img_dir = os.path.join(current_dir, "img_dir") #Path to the folder where your `png` is
player_img = pygame.image.load(os.path.join(img_dir, "space-invaders.png"))
Instead of "img_dir" you need to put the name of your folder, or the path, depending on the folder location.

Python Cocos2d can't find resource image after resizing it

I'm trying to resize an image in Python and then load a cocos2d sprite with the resized image. However, trying to initialize a cocos2d sprite results in an error that the resource can't be found. Example code to reproduce the problem:
from pathlib import Path
import cocos
from PIL import Image
im = Image.open("in.jpg")
im.thumbnail((600, 900))
im.save("out.jpg", "JPEG")
im.close()
file = Path("out.jpg")
if file.is_file():
print("File exists")
sprite = cocos.sprite.Sprite("out.jpg")
This results in the error
pyglet.resource.ResourceNotFoundException: Resource "out.jpg" was not found on the path. Ensure that the filename has the correct captialisation.
However, the output is:
File exists
Running it a second time doesn't give errors, since out.jpg has been created in the previous run. Deleting out.jpg and running it again produces the error.
Adding an im.close() didn't solve the problem.
The OS is Windows 10 with Python version 3.6.4.
It turned out to be the method used in pyglet to load a resource. I had to reindex the images. The files in the images directory where dynamically added and pyglet creates an index of existing images. See https://stackoverflow.com/a/16438410/6350693 for the answer.

I can't load an image in pygame/python2.7

Can someone help me load an image? It says "error: can't open tux.jpg:
import sys, pygame
pygame.init()
size = width, height = 600,400
screen = pygame.display.set_mode(size)
tux = pygame.image.load("tux.jpg")
screen.blit(tux,(200,200)) #Displays Tux On Screen
pygame.display.flip()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
Please check that you have the image file within the directory that you are working in.
Using an absolute path may also be an option, for example:
tux = pygame.image.load("C:\\path\\to\\game\\tux.jpg")
For more information, please see this answer here.
The path you entered comes out as "./tux.png", i.e. the current working directory. Either place the file at the same location as your .py file (hence the default working directory for the script) or define the path to your image file.
For game file ordering, images are often in separate directories to the game scripts, The best way to do this is the os module. os.getcwd() gives the current working directory, and can be modified to the image directory using os.path.join. e.g.
game/
game.py
images/
tux.jgp
game.py uses pygame.load(os.path.join(os.getcwd(), "images")
(or define a datapath variable at the top in the same way if using lots of images!)

Categories

Resources