pygame.error: Couldn't open image.bmp

4.1k views Asked by At

Whenever I run this code the message pygame.error: Couldn't open ship.bmp appears. I am keeping the file ship.bmp in the same place as my code. I would appreciate any help.

import sys
import pygame

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width,screen_height))
bg_color = (0, 13, 114)
pygame.display.set_caption('space invaders')

shipImg = pygame.image.load("ship.bmp")

def ship(x,y):
    screen.blit(shipImg, (x,y))

x = (screen_width * 0.45)
y = (screen_height * 0.8)

crashed = False
while not crashed:

    #keyboard events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
    screen.fill(bg_color)
    ship(x,y)
    pygame.display.flip()
pygame.quit()
quit()
3

There are 3 answers

0
emorphus On

I tried your code and it worked fine. See that the image is in the ROOT DIRECTORY. That is the same folder where you save this script/py file. The other reason could be that there are hidden characters in your file name. This happened to me several times. try rename function, delete the entire name including the file extension and rename the file with the same ext, brand new.

0
storenth On

Do you run this code in Unix OS? If so you need change your working directory to run this file.py! in terminal type with cd command to your directory where files saved! then run python with te same path and will be work fine!

0
Ochibobo On

Use print os.getwd() as the first line of your script/py program to see which folder you are actually starting from. If your image happens to be in a sub-directory of the main folder (which happens not to appear on the output of os.getwd()), make sure to include it in your image path such that instead of writing only 'ship.bmp' when loading the image, you write 'subdirectory/ship.bmp' as your path.