Reputation: 137
I am new to python and created a small game. I want to add a background image, but is is not working. The image is not displayed.
i tried it with the following code:
background = pygame.image.load("images\\background.png")
screen.blit(background,(0,0))
Upvotes: 0
Views: 3107
Reputation: 14906
The code in the question does not really illustrate the problem. But if the code is generating the error:
background = pygame.image.load('images/background.png')
pygame.error: Couldn't open images/background.png
Then it is simply that PyGame can't find the specified image file.
However I expect that your code is simply not "flushing" the updates to the window / screen with a call to pygame.display.flip()
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
### MAIN
pygame.init()
SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), SURFACE )
pygame.display.set_caption("Background Image")
background_image = pygame.image.load('images/grass.png')
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# Movement keys
keys = pygame.key.get_pressed()
if ( keys[pygame.K_UP] ):
print("up")
#elif ...
# Update the window, but not more than 60fps
window.blit( background_image, ( 0,0 ) )
pygame.display.flip() # <-- Flush drawing ops to the screen
# Clamp FPS
clock.tick_busy_loop( 60 )
pygame.quit()
Note the 4th-last line.
Upvotes: 2
Reputation:
Take a look at this page on StackOverflow. It has multiple solutions that you can use. I'll write one of them here.
You can make an image the size of your game window, then before anything else is displayed, blit it to (0,0).
bg = pygame.image.load("background.png")
#INSIDE OF THE GAME LOOP
gameDisplay.blit(bg, (0, 0))
#OTHER GAME ITEMS
I hope this helps you!
Upvotes: 0