How to get Pygame to open images - python

I've been trying to find a solution to this problem for a while now: I'm trying to display an image using the Pygame module in python but I always get this error:
File "C:/Users/Brandon/PycharmProjects/UnstableUnicorns/UnstableUnicorns Test.py", line 13, in <module>
Baby_Narwhal = pygame.image.load(r"Baby Narwhal.png").convert()
pygame.error: Couldn't open Baby Narwhal.png
(Yes I know there are spaces but there are a lot of images that I want to display and they all have spaces in their names)
I've tried putting the whole path file, using .convert(), using backslashes (and removing the spaces didn't work either) and adding interpreter paths. I've asked this question multiple times on this site and I haven't gotten a working answer. Help.
import pygame
import os
import sys
from time import sleep
print(os.getcwd())
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
Baby_Narwhal = pygame.image.load(r"Baby Narwhal.png").convert()
pygame.init()
xDisplay = 1000
yDisplay = 500
white = (255, 255, 255)
def main():
display = pygame.display.set_mode((xDisplay, yDisplay))
while True:
display.fill(white)
display.blit(Baby_Narwhal, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
main()

I think your solution would to get the path of the image or whatever you need. I had this problem about a month ago, and getting the exact path fixed it for me. You should also verify that you have the correct name of the file in your code. Hope this helps.. Good luck! :)
Example: C:/User/Desktop...
(im a linux guy) I don't usually use Windows so I don't know paths off the top of my head. Additionally, you could try and put your pygame file and image into your same folder and just get the name of your image/file.

Related

Having difficulty using pygame.image.load() [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 1 year ago.
I am trying to use the pygame.image.load() function to create an image while following a tutorial.
This is the code that I used:
import pygame
pygame.init()
running=True
screen = pygame.display.set_mode((1350, 700))
pygame.display.update()
wheel = pygame.image.load('wheel_image.png')
while running:
screen.fill(0, 0, 0)
for event in pygame.event.get():
if event.type ==pygame.QUIT:
running=False
screen.blit(wheel, (675, 350))
pygame.display.update()
But when I run it, it gives this error message:
line 6, in <module>
wheel = pygame.image.load('wheel_image.png')
pygame.error: Couldn't open wheel_image.png
I have the png file in the same directory as my code, so have I made an error in my code or what could be causing this?
Whether the file can be found depends on the location from where you call your code. That's inconvenient so better calculate the project's base path using the __file__ property:
from pathlib import Path
BASE = Path(__file__).resolve().parent
wheel_path = BASE / 'wheel_image.png'
wheel = pygame.image.load(wheel_path)
If you use an older version of pygame that can't handle Path objects, manually turn it into a string:
wheel_path = str(BASE / 'wheel_image.png')

Only some pygame projects works after converted from .py to .exe [duplicate]

This question already has answers here:
How can I convert pygame to exe?
(6 answers)
Pygame2Exe Errors that I can't fix
(3 answers)
Closed 1 year ago.
I want to be able to convert .py to .exe for python 3 pygame 1.9.4 projects (on my Windows 10 computer), and I have successfully converted some files by using auto py to exe (one file, console based):
https://nitratine.net/blog/post/auto-py-to-exe/.
For example, I tried to convert the code that is quite far up on this site:
http://openbookproject.net/thinkcs/python/english3e/pygame.html. That is:
import pygame
def main():
""" Set up the game and run the main game loop """
pygame.init() # Prepare the pygame module for use
surface_sz = 480 # Desired physical surface size, in pixels.
# Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((surface_sz, surface_sz))
# Set up some data to describe a small rectangle and its color
small_rect = (300, 200, 150, 90)
some_color = (255, 0, 0) # A color is a mix of (Red, Green, Blue)
while True:
ev = pygame.event.poll() # Look for any event
if ev.type == pygame.QUIT: # Window close button clicked?
break # ... leave game loop
# Update your game objects and data structures here...
# We draw everything from scratch on each frame.
# So first fill everything with the background color
main_surface.fill((0, 200, 255))
# Overpaint a smaller rectangle on the main surface
main_surface.fill(some_color, small_rect)
# Now the surface is ready, tell pygame to display it!
pygame.display.flip()
pygame.quit() # Once we leave the loop, close the window.
main()
The .exe file ran as it should when opened. However, some programs that I write are only partially functioning after the conversion.
One such program would be:
import pygame as pg
def main():
pg.init()
pg.display.set_caption('Some Caption')
screen = pg.display.set_mode((640, 480))
afont = pg.font.SysFont("some_font", 32)
done=False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
screen.fill(0)
sometext = afont.render("Amazing text"
.format(0, 0), True, (250,200,250))
screen.blit(sometext, (10, 50))
pg.display.flip()
if __name__.endswith('__main__'):
main()
pg.quit()
After converted to exe, when I open it, some text about pygame appears and also the screen that is meant to pop up, showing the caption which I've set ('Some Caption'). The screen which popped up is however black and closes after a while, not showing what it should. However, I did get my exe file without any errors (which I could see anyway in the Output of the GUI which I used for the conversion i.e. auto py to exe). So in search of solutions I found this website:
https://nitratine.net/blog/post/issues-when-using-auto-py-to-exe/.
There were alot about error messages and general information but the thing I saw about program that opens but not doing what it should before closing was:
The Terminal Just Opens and Closes But There Are No Errors If you
double click to run your Python script, what happens? Does it open and
close also? That means this tool has done it's job correctly and the
script is finishing just like it should.
You most likely think the output should stay visible because you are
always using IDLE or an IDE and that's what those tools do. Add a
statement like input() at the end of your script to block execution
and wait for you to press enter before closing.
This, is not the solution for my problem since my program works if I double click on the python script. However, I think that it has a good point i.e that there might be something in my code that do not handle the conversion well, which is probable since the code from http://openbookproject.net/thinkcs/python/english3e/pygame.html did work after being converted to .exe when the same method was used.
My question is therefore, what is it that make my code not work after the conversion from .py to .exe?, and in that case, in what way might it be fixable?. The knowledge of what works and not when it comes to the converting .py to .exe would enable more programs to function correctly when they are .exe.
Thank you

Specific .wav file getting shortened and distorted

I'm having trouble playing this single .wav file: http://s000.tinyupload.com/?file_id=05630565903583383733
All I get is a quick "tick" sound. Tried another .wav and it plays fine. Tried resampling, and converting to .ogg, still same issue.
.get_length() returns 0.00031746 when the original .wav length is 176ms.
Changing pygame.mixer.init parameters alters .get_length() but still a very low value.
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800, 600), 0, 0)
blip_sound = pygame.mixer.Sound('C:\Users\me\Desktop\blip.wav')
blip_sound.play()
print blip_sound.get_length()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
SOLVED: I changed to use only 'blip.wav' instead of 'C:\users\me\Desktop\blip.wav' just to organize things (putting the .wav in the same folder of my script) and the sound started working!
It's strange because one .wav file it could read from desktop, but the other it couldn't... Also I learned that no error is raised when pygame can't open a sound file... The sound just won't play (different from images, where the code won't compile).

error: Couldn't open .png file (Python - Pygame library)

import pygame
import os
import sys
import time
from pygame.locals import *
pygame.init()
#Colours here
RED = pygame.Color(150, 0, 0)
GREEN = pygame.Color( 0, 150, 0)
BLUE = pygame.Color( 0, 0, 150)
BLACK = pygame.Color( 0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
FPS = pygame.time.Clock()
WIDTH = 1024
HEIGHT = 768
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Penaldo v0.1')
#Set BACKGROUND to an instance of pygame.Surface, which will get its coordinates from the previous ones we assigned to the game's display
BACKGROUND = pygame.Surface((SCREEN.get_width(), SCREEN.get_height()))
SCREEN.blit(BACKGROUND, (0, 0))
key_press = pygame.key.get_pressed()
class Player():
def __init__(self):
#Try to load our sprite.
#'r' makes it a raw string so it ignores escape sequences
self.player = pygame.image.load(r"\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png")
self.p_rect = self.player.get_rect()
#Spawn the player just in the middle of our screen
self.p_rect.centerx = WIDTH / 2
self.p_rect.centery = HEIGHT / 2
def move(self):
if key_press[UP]:
self.p_rect.y -= 5
elif key_press[DOWN]:
self.p_rect.y += 5
elif key_press[LEFT]:
self.p_rect.x -= 5
elif key_press[RIGHT]:
self.p_rect.x += 5
while True:
for event in pygame.event.get():
if event.type == QUIT:
#Some IDLE friendliness (prevents from hanging)
pygame.quit()
sys.exit()
BACKGROUND.fill(GREEN)
p1 = Player()
# FOR THE GAME TO WORK you have to include this one inside main while-loop (no display update = no game)
pygame.display.update()
FPS.tick(40)
The full error message is:
Traceback (most recent call last):
File "C:\Users\NZXT\Documents\GameLab\Penaldo\game\version1\Penaldo.py", line 79, in <module>
p1 = Player()
File "C:\Users\NZXT\Documents\GameLab\Penaldo\game\version1\Penaldo.py", line 49, in __init__
self.player = pygame.image.load(r"\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png")
error: Couldn't open \..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
I read a few questions such as Python 2.6: "Couldn't open image" error, error: Couldn't open Image and I've tried to implement the different tips but the window just goes black and hangs.
I have a few ideas.
Perhaps you entered the image name incorrectly.
Or the folders in the path don't exist.
You may have misplaced the file.
You didn't consider your operating system.
And here are a few suggestions:
Rather than backslashes, use os.path.join('..', '..', 'resources', 'mario_sprite_by_killer828-d3iw0tz.png') inside pygame.image.load. This will correctly load for Linux, Windows, and Mac which ever one you may be using.
Try using a more organized arrangement so that backtracking that far will not be necessary.
Check and/or rename the file to ensure you're using the correct path. Make sure file is actually a png.
Use os.chdir to change the current directory to the folder in which the image is contained then use pygame.image.load('mario_sprite_by_killer828-d3iw0tz.png') as you normally would.
Give these a try. By the way, your key events won't work as expected because the key_press variable isn't continuously updated, you simply initialized it at the beginning.
Looking at that /../../ I see you are trying to look for a dynamic file path depending on the users file path to the image? That isn't how it works, and that is why you are getting that error. It can't find the .PNG file because there is no such thing as :
\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
You can look at this article that explains it well: Relative paths in Python
Usually to ensure the image file can be loaded without raising errors about not being able to find your image, put that image in the same folder as your program. As for PyCharm users, just copy and paste the file into your current project that has the correct program. Using os.path.join() might be better if you dislike doing it the other way. Try going to the Pygame Docs for more information if you have time. Your problem is that you are using backward slashes () instead of using forward slashes (/). You should change your path from:
\..\..\resources\mario_sprite_by_killer828-d3iw0tz.png
to:
/../../resources/mario_sprite_by_killer828-d3iw0tz.png
Credit for this answer and the real explanation of your problem can be found in this problem in Stack Overflow: Python 2.6: "Couldn't open image" error
I hope this helps you! Oh, if the question link above doesn't help, use the Pygame Docs link instead.

error: couldn't open .png [duplicate]

This question already has answers here:
pygame.error "couldn't open image.png" only in command prompt
(3 answers)
Closed 2 years ago.
Can someone help me identify where I went wrong? Thanks. I get: pygame.error: Couldn't open space.png. My code is as follows:
import random, math, pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("orbit demo")
space = pygame.image.load("space.png").convert()
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
sys.exit()
#draw backgroud
screen.blit(space, (0,0))
pygame.display.flip()
You may have to do the following:
import pygame
import os
try:
# load from subfolder 'data'
background = pygame.image.load(os.path.join("data","background640x480_a.jpg"))
ball = pygame.image.load(os.path.join("data","snake.gif"))
except:
raise UserWarning, "Unable to find the images in the folder 'data' :-( "
This was obtained from the Python Game Book website. Basically you tell it where to look (in the code above, it is the data folder. If it cannot find it, it reports the User Warning.
So in the example that I'm writing for my game, I have an images folder, so I do this
self.image = background = pygame.image.load(os.path.join("images","starship.png")).convert()
I am a newbie to this, but reading suggests this is how you do it.
EDIT - The other reason could be. Is it the correct format (e.g. png) or have you named the file something else?
Try specifying the full path of the image(s), example: C:/Python34/your_folder/file_name.png
Note: in your python code to refer to a path you can't use "\", must use "/"
the "\" has a specific meaning in python.
For me the answer was I was not running the command from within the folder containing the game file. Both my .py file and .png file are in the top level, so I cd into that and ran and it worked.

Categories