0

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()
tshepang
  • 12,111
  • 21
  • 91
  • 136
Mark
  • 1

2 Answers2

1

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.

Community
  • 1
  • 1
gurpreet-
  • 509
  • 8
  • 18
1

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!)

Tehsmeely
  • 188
  • 6