Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have an image appear in python/pygame

Tags:

python

pygame

I am trying to learn to make a basic game using pygame. I want to import and display an image in .png format. so far my attempt has been:

import pygame
from pygame.locals import*
pygame.image.load('clouds.png')

white = (255, 64, 64)
w = 640
h = 480
screen = pygame.display.set_mode((w, h))
screen.fill((white))
running = 1

while running:
    screen.fill((white))

    pygame.display.flip()

The Image (clouds.png) is in the same folder as the file. when i try to run this i get an error:

Traceback (most recent call last):
  File "C:\Users\Enrique\Dropbox\gamez.py", line 3, in <module>
    pygame.image.load('clouds.png')
error: Couldn't open clouds.png
like image 659
enrique2334 Avatar asked Jan 07 '12 03:01

enrique2334


People also ask

How do I make an image appear in Python?

Import the module Image from PIL. Create a variable img and then call the function open() in it. Give the path that has the image file. Call the show() function in joint with img variable through the dot operator “.”.

Can pygame use PNG?

Pygame is able to load images onto Surface objects from PNG, JPG, GIF, and BMP image files.

How do you reflect an image in pygame?

To flip the image we need to use pygame. transform. flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs.


2 Answers

Here you go. It blits the image to 0,0. Your other problem is that your pyimage doesn't seem to be built with png support

import pygame
from pygame.locals import*
img = pygame.image.load('clouds.bmp')

white = (255, 64, 64)
w = 640
h = 480
screen = pygame.display.set_mode((w, h))
screen.fill((white))
running = 1

while running:
    screen.fill((white))
    screen.blit(img,(0,0))
    pygame.display.flip()
like image 73
rsaxvc Avatar answered Oct 05 '22 08:10

rsaxvc


Here is an image handling block that I use in my games:

import os, sys
...
-snip-
...
def load_image(name, colorkey=None):
    fullname = os.path.join('images', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

You can copy-paste this in any game and it will work. os and sys need to be imported into your game or else it won't work.

like image 34
Oventoaster Avatar answered Oct 05 '22 10:10

Oventoaster