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!)
Related
There's something I want to make, so I'm learning tkinter.
The relative route is not recognized.
Example code.
Suppose that hyunju.png is in the corresponding .py folder.
import tkinter
root = tkinter.Tk()
root.title("tk")
canvas = tkinter.Canvas(root, width=400, height=600)
canvas.pack()
gazou = tkinter.PhotoImage(file="hyunju.png")
canvas.create_image(200, 300, image=gazou)
root.mainloop()
tkinter.TclError: couldn't open "hyunju.png": no such file or
directory
I'm having a hard time because if I use Copy path, there will be a problem when I share or change files.
The editor used is VS code and OS is window 10.
help for me thank you
Depending on hardcoded relative paths should be avoided in this scenario, as they're often times unreliable. Depending on your IDE and even OS it may work or not.
Thus, You should choose a more dynamic better an approach like the following:
import pathlib, os
img_file_name = "hyunju.png"
current_dir = pathlib.Path(__file__).parent.resolve() # current directory
img_path = os.path.join(current_dir, img_file_name) # join with your image's file name
As long as the image file is guaranteed to be in the same directory as the script being executed, it does not matter what IDE / OS you're on - it will work.
I had the same problem and I don't know if it might be the same case for you, just check that you are opening the whole project and not just the .py file if you are working on an IDE like, for example, Visual Studio Code, because else it won't be able to find any relatives paths
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.
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'))
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'm using the code:
import pygame, sys, datetime
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen.fill((0, 0, 0, 255))
pygame.display.set_caption("TESTIFICATE")
if datetime.date.today().month == 12 and datetime.date.today().day == 25:
pygame.mixer.music.load("8bit-jingle-twist.mp3")
print("Merry Christmas!")
else:
pygame.mixer.music.load("timeless-mountains.mp3")
print("Loading Music...")
pygame.mixer.music.play(-1, 0.0)
print("Playing Background Music...")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Both 8bit-jingle-twist.mp3 and timeless-mountains.mp3 exist and can be played by VLC. My volume is on, as is my confusion.
Are you sure you are looking for them in the correct directory?
Try specifying the full path, ie
"c:/programs/mygame/music/8bit-jingle-twist.mp3"
Very strange, I simply copied your code and just changed the audio files to ones I had, and it worked perfectly fine.
I think therefore it has something to do with the files themselves.
It could be as Hugh Bothwell pointed out, the file path. In which case you could do three things:
Use the whole file path:
pygame.mixer.music.load("C:/blah/blah/blah/8bit-jingle-twist.mp3")
Use no file path (The file must then be in the same folder as the program)
pygame.mixer.music.load("8bit-jingle-twist.mp3")
Or use a one folder jump, where you have a folder inside the same folder as your program.
So for example you have your program in "My Documents", then you make another folder called "Music for Pygame" inside of "My Documents". Then the code would be:
pygame.mixer.music.load("Music for Pygame/8bit-jingle-twist.mp3")
I mostly use the last option, so that you can keep your files organized by having a folder for music, a folder for images, etc. and the program would still work if you moved the folder it was in.
Of course it could also be the audio file itself. Make sure it really is a .mp3 and that it plays fine (VLC is too awesome and can play anything, try playing it on Windows media or something just in case)
Also if using Windows 7 OS, try running it as an administrator and it might fix the problem.
(I ran the code on Windows XP and it worked fine just now)
NEW ANSWER:
if you saved your mp3 file as 'filename.mp3', and you wrote down the .mp3 file extension yourself, then the filename in pygame's pygame.mixer.music.load() function must be written as 'filename.mp3.mp3', because python expects you to add the .mp3. Sometimes the .mp3 is already included in the filename if you manually saved it as that.
Therefore, try this:
pygame.mixer.music.load('filename.mp3.mp3')