error: Couldn't open Image - python

I'm working on a time based movement program in pygame. And I keep receiving this error.
Traceback (most recent call last):
File "C:\Documents and Settings\Mohammad Raza\Desktop\Python
Scripts\TimeBasedMovement.py", line 11, in <module>
background = pygame.image.load(background_image_filename).convert()
error: Couldn't open Wolf.jpg
I thought perhaps I deleted the image, but I checked and the image is not deleted. It is saved as the name "Wolf" and stored as a JPEG image.
Here is the entire code below.
background_image_filename = 'Wolf.jpg'
sprite_image_filename = 'Cartoon.jpg'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprite_image_filename)
clock = pygame.time.Clock()
x = 0.
speed = 250
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background,(0,0))
screen.blit(sprite,(x,100))
time_passed = clock.tick()
time_passed_seconds = time_passed_seconds / 1000.0
distance_moved = time_passed_seconds * speed
x += distance_moved
if x > 640.:
x -= 640.
pygame.display.update()

Also make sure the image is in the current working directory.
fullname = os.path.join('data', name)
image = pygame.image.load(fullname)

Also it should be
time_passed_seconds = time_passed / 1000.

Related

Image Not Found, When The Image Is Right There? [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 12 months ago.
Hey everybody, I am making a pixel runner style game, and when I try to load a random image using a method I always use, it comes up with the error:
Traceback (most recent call last):
File "c:\Users\name\Documents\Python\PixelRunnerMain\PixelRunner.py", line 22, in
png1 = pygame.image.load("1.png")
FileNotFoundError: No file '1.png' found in working directory 'C:\Users\chizl\Documents'.
The file is in the exact same directory as the images! Please help. (also, I want HELP, dont just come here to correct my question.)
import pygame, random
#initialise pygame
pygame.init()
#window values
win = pygame.display.set_mode((416,256))
pygame.display.set_caption("Pixel Runner")
run = True
#player values
x = 192
y = 144
width = 16
height = 16
vel = 12
#enemy values
e_x = 0
e_y = 0
e_vel = 12
png1 = pygame.image.load("1.png")
png2 = pygame.image.load("2.png")
e_types = [png1, png2]
e_type = random.choice(e_types)
#while loop (all main code goes here)
while run:
pygame.time.delay(80)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#key presses
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel-16:
x -= vel
if keys[pygame.K_RIGHT] and x < 390:
x += vel
#gravity
e_y = e_y + e_vel
if e_y > 256:
e_y = 0
#player gravity or something
if win.get_at((x,y)) == (0,0,0) or win.get_at((x+16,y)) == (0,0,0):
y += 12
e_type = random.choice(e_types)
#more window stuff
win.fill((255,255,255))
pygame.draw.rect(win, (255,0,0), (x, y, width, height))
win.blit(win, e_type, (0,e_y))
pygame.display.update()
pygame.quit()
how about get a current directory?
# Import the os module
import os
# Get the current working directory
cwd = os.getcwd()
and check your directory if it is correct
# Print the current working directory
print("Current working directory: {0}".format(cwd))
if everything is correct, replace the code where you call the image with :
png1 = pygame.image.load(cwd+"1.png")

Displaying an image with pygame

I am having a problem with displaying an image in pygame. The image is in the same directory/folder but it still has an error. This error popped out of the blue and I'm not sure how to fix it... My code below
import pygame, sys
from pygame.constants import QUIT
pygame.init()
GameSprite = pygame.image.load('GameSprite.png')
GameSprite = pygame.transform.scale(GameSprite,(200, 200))
def main():
x = 100
y = 100
velocity = 0
velocity = pygame.Vector2()
velocity.xy = 3, 0
acceleration = 0.1
DISPLAY = pygame.display.set_mode((570, 570))
pygame.display.set_caption("Flappy Bird Related Game")
WHITE = (255,255,255)
BLUE = (0, 0, 255)
while True:
DISPLAY.fill(WHITE)
#pygame.draw.rect(DISPLAY,BLUE,(x,y,50,50))
DISPLAY.blit(GameSprite,(x,y))
y += velocity.y
x += velocity.x
velocity.y += acceleration
if x + 50 > DISPLAY.get_width():
velocity.x = -3
if x < 0:
velocity.x = 3
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
velocity.y = -4.2
pygame.display.update()
pygame.time.delay(10)
main()
It is not sufficient to copy the image files in the project directory. You also need to set the working directory.
The image file path has to be relative to the current working directory. The working directory can be different to the directory of the python script.
The name and path of the script file can be retrieved with __file__. The current working directory can be set with os.chdir(path).
Add the following lines of code at the beginning of your script to set the working directory to the same as the script's directory:
import os
import pygame, sys
from pygame.constants import QUIT
os.chdir(os.path.dirname(os.path.abspath(__file__)))
pygame.init()
GameSprite = pygame.image.load('GameSprite.png')
To make things simpler instead of writing "GameSprite.png" try adding the path to the file.
Example:
if the GameSprite.png is in the location C://Users/person/Desktop
Replace GameSprite = pygame.image.load('GameSprite.png')
with
GameSprite = pygame.image.load('C://Users/person/Desktop/GameSprite.png')
Just put the file location in pygame.image.load()

Getting pygame.Surface Error. How do I fix?

I use Python 3.7.4 and Pygame 1.9.6. I'm trying to create just a test game so I can save data like a score per say using pickle this is my first time. But I'll get down that path once I'm done with the test game.
I'm getting an error two separate occasions in ball(ballX[i], ballY[i], i) and in screen.blit(ballImg, (x, y), i). It's a TypeError: arugument 1 must be pygame.Surface, not list.
Full Trace Back:
Traceback (most recent call last):
File "C:Test/main.py", line 128, in <module>
ball(ballX[i], ballY[i], i)
File "C:/Test/main.py", line 66, in ball
screen.blit(ballImg, (x, y), i)
The code:
import pygame
import random
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg, (x, y), i)
running = True
while running:
'''The key stuff and what not'''
'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
pygame.display.update()
I'm not understanding what I'm doing wrong in my function/list or evening bliting the image. I feel like I'm doing everything right filling out the parameters, etc. I appreciate the advice. So thank you.
A few things:
As #Ewong mentioned, you are passing ballImg to blit instead of ballImg[i]
You're not processing OS messages, so the program will freeze
Try this code:
import pygame
import random
scr_width = 800
scr_height = 600
screen = pygame.display.set_mode((scr_width, scr_height))
# Ball
ballImg = []
ballX = []
ballY = []
num_of_balls = 4
for i in range(num_of_balls):
ballImg.append(pygame.image.load('ball.png'))
ballX.append(random.randint(0, 736))
ballY.append(random.randint(50, 535))
#'''This code is above the while running loop'''
def ball(x, y, i):
screen.blit(ballImg[i], (x, y))
running = True
while running:
#'''The key stuff and what not'''
#'''I have the screen color load before the image appears'''
for i in range(num_of_balls):
ball(ballX[i], ballY[i], i)
for event in pygame.event.get(): # process OS messages
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.display.update()

Why is this nameError occurring

I am 9 and self teaching, please be kind and keep that in mind when you reply, thank you very much for your time.
I have the image Bluecar.png and the following code in the same file:
import pygame, time
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.setmode((width, height))
pygame.display.flip()
player = Bluecar.png
screen.blit(player)
while True:
time.sleep(0.1)
But, it causes this error:
Traceback (most recent call last):
File "/home/pi/escape/listings/listings/listing7-2.py", line 7, in <module>
player = Bluecar.png
NameError: name 'Bluecar' is not defined.
Also, after fixing the NameError, I think an Attribute Error will occur.
You probably want to use the pygame.image.load() function
import pygame, time
import os.path
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.setmode((width, height))
pygame.display.flip()
filepath = os.path.dirname(__file__)
x = 0 #x co-ordinate
y = 0 #y co-ordinate
player = pygame.image.load(os.path.join(filepath, "Bluecar.png"))
screen.blit(player, (x, y))
Edit
Included os.path.join to ensure image loaded from the directory of the python file.

Simple analog clock get slows then Error shows up with Pygame

I have started to learn pygame and I code a simple analog clock.
import sys, pygame
pygame.init()
white = 255, 255, 255
size = width, height = 480, 480
screen = pygame.display.set_mode(size)
minute_hand = pygame.image.load('minute_hand.png')
minute_hand_rect = minute_hand.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
center = minute_hand_rect.center
rotate = pygame.transform.rotate
minute_hand = rotate(minute_hand, -1)
minute_hand_rect = minute_hand.get_rect(center=center)
screen.fill(white)
screen.blit(minute_hand, minute_hand_rect)
pygame.display.update()
pygame.time.delay(100)
But my hand_clock getting slower and slower for a while then stops to running and says:
Traceback (most recent call last):
File "clock.py", line 21, in <module>
minute_hand = rotate(minute_hand, -1)
pygame.error: Width or height is too large
Apparently I'm doing something so wrong but I couldn't figure what is wrong.
The problem is the minute_hand = rotate(minute_hand, -1)
This is using the last frames image to generate the next, which means storing a whole load of transformation data each time it updates. It also gave me an 'Out of memory error' and as you'll notice causes the image to get distorted over time
The solution is to keep using the original image and rotate it more
Shown below:
import sys, pygame
pygame.init()
white = 255, 255, 255
size = width, height = 480, 480
screen = pygame.display.set_mode(size)
minute_hand = pygame.image.load('box4.jpg')
minute_hand_rect = minute_hand.get_rect()
angle = 0
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
center = minute_hand_rect.center
rotate = pygame.transform.rotate
new_image = rotate(minute_hand, angle)
new_image_rect = new.get_rect(center=center)
angle -= 1
if angle == -360:
angle = 0
screen.fill(white)
screen.blit(new, new_rect)
pygame.display.update()
pygame.time.delay(100)
This takes an angle that changes every frame and applies it to the original
Hope this helps.

Categories

Resources