# Image display in pygame wont work.

This topic is 3012 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

""" mypygame.py
draw an image on the screen"""

import pygame
pygame.init()

def main():
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Display an image")

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((96, 96, 0))

mypygame = mypygame.convert()

clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False

screen.blit(background, (0, 0))
screen.blit(example, (96, 96))

pygame.display.flip()

if __name__ == "__main__":
main()


When I save and run the module, all I get is a black window. What am I doing wrong? BTW I'm using pygame 1.9.1 the version that's required for 2.5.4. [Edited by - Unknownforest on November 14, 2009 9:15:11 PM]

##### Share on other sites
Quote:
 Original post by Unknownforestmypygame = pygame.image.load("example.png")mypygame = mypygame.convert()...screen.blit(background, (0, 0))screen.blit(example, (96, 96))...pygame.display.flip()

Here is the relevant portion of yr code where the problem is. Yr line, screen.blit(example, (96, 96)) should be screen.blit(mypygame, (96, 96)). Right?

Check if this works.

##### Share on other sites
It worked with small PNGs but when I went with a PNG that's 640x400 it didn't work.

##### Share on other sites
Quote:
 Original post by Unknownforest... but when I went with a PNG that's 640x400 it didn't work.

What do you mean by this? Can you please be more specific?

##### Share on other sites
Quote:
Original post by signal_
Quote:
 Original post by Unknownforest... but when I went with a PNG that's 640x400 it didn't work.

What do you mean by this? Can you please be more specific?

The image won't show up in the window.

##### Share on other sites
Okay. I just downloaded Pygame & Python. I wiped this comp one month ago so I didn't re-install it yet.

Try this:
import pygame, sys, ospygame.init()from pygame.locals import *def GetInput():    key = pygame.key.get_pressed()     for event in pygame.event.get():         if event.type == pygame.QUIT or key[K_ESCAPE]:             pygame.quit();            sys.exit() def main():    screen = pygame.display.set_mode((640, 480))        pygame.display.set_caption("Display an image")    background = pygame.Surface(screen.get_size())    background = background.convert()    background.fill((96, 96, 0))    img0 = pygame.image.load("0.png").convert()    img1 = pygame.image.load("1.png").convert()        clock = pygame.time.Clock()    keepGoing = True    imgX = 0;    imgY = 0;    directionX = 1;    directionY = 1;        while keepGoing:        clock.tick(30)        GetInput()        screen.blit(background, (0, 0))        screen.blit(img0, (0, 0))        screen.blit(img1, (imgX, imgY))        if imgX < 0 or imgX > (screen.get_width() - img1.get_width()):            directionX *= -1        if imgY < 0 or imgY > (screen.get_height() - img1.get_height()):            directionY *= -1        imgX += directionX        imgY += directionY        pygame.display.flip()if __name__ == "__main__":    main()

Some notes:

1. I used 2 images to make this program: img0 and img1. img0, for me, is 640x480 so it covers the screen. img1 is a 96x96 sprite that bounces around the screen. I added some simple movement and screen-edge collision detection.

2. Use 'source' tags when posting code; they preserve the formatting. You can just copy-n-paste mine....

3. Try this. It should work. If it doesn't something is wrong on yr end (I'm using the same Python and Pygame as you are).

##### Share on other sites
 import pygame, sys, ospygame.init()from pygame.locals import *def GetInput():    key = pygame.key.get_pressed()     for event in pygame.event.get():         if event.type == pygame.QUIT or key[K_ESCAPE]:             pygame.quit();            sys.exit() def main():    screen = pygame.display.set_mode((640, 480))        pygame.display.set_caption("Display an image")    background = pygame.Surface(screen.get_size())    background = background.convert()    background.fill((96, 96, 0))    sky6 = pygame.image.load("6.png").convert()    sky4 = pygame.image.load("4.png").convert()        clock = pygame.time.Clock()    keepGoing = True    skyX = 0;    skyY = 0;    directionX = 1;    directionY = 1;        while keepGoing:        clock.tick(30)        GetInput()        screen.blit(background, (0, 0))        screen.blit(sky6, (0, 0))        screen.blit(sky4, (skyX, skyY))        if skyX < 0 or skyX > (screen.get_width() - sky4.get_width()):            directionX *= -1        if skyY < 0 or skyY > (screen.get_height() - sky4.get_height()):            directionY *= -1        sky4X += directionX        sky4Y += directionY        pygame.display.flip()if __name__ == "__main__":    main()

I use the approach of using sky6 as the background since it's 0, 0. And then I used sky4 for movement. Both are 96x96 .pngs. But all I get is.

Traceback (most recent call last):  File "C:\Documents and Settings\anonymous\Desktop\thatfolder\pygame.py", line 1, in <module>    import pygame, sys, os  File "C:\Documents and Settings\anonymous\Desktop\thatfolder\pygame.py", line 2, in <module>    pygame.init()AttributeError: 'module' object has no attribute 'init'

What wrong here? What did I do wrong in placing the pngs?

##### Share on other sites
Are you sure you have exactly:

import pygame, sys, os
pygame.init()

at the start of your pygame.py? No weird spaces or anything else?

##### Share on other sites
Quote:
 Original post by mattdAre you sure you have exactly:import pygame, sys, ospygame.init()at the start of your pygame.py? No weird spaces or anything else?

Yeah, OP, make sure you preserve formatting. Why don't you try typing or copy-pasting the code into IDLE. That way you can see any error messages that pop up. Maybe something is wrong with yr setup since the code is running fine on my pc.

So try inputting the code into IDLE line-by-line and post the results. Here is my result from the code that I typed up:

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.    ****************************************************************    Personal firewall software may warn about the connection IDLE    makes to its subprocess using this computer's internal loopback    interface.  This connection is not visible on any external    interface and no data is sent to or received from the Internet.    ****************************************************************    IDLE 1.2.4      ==== No Subprocess ====>>> import pygame, sys, os>>> >>> from pygame.locals import *>>> pygame.init()(6, 0)>>> screen = pygame.display.set_mode((640, 480))>>> pygame.display.set_caption("Display an image")>>> background = pygame.Surface(screen.get_size())>>> background = background.convert()>>> background.fill((96, 96, 0))<rect(0, 0, 640, 480)>>>> img0 = pygame.image.load("0.png").convert()>>> img1 = pygame.image.load("1.png").convert()>>> imgX = 0;>>> imgY = 0;>>> screen.blit(background, (0, 0))<rect(0, 0, 640, 480)>>>> screen.blit(img0, (0, 0))<rect(0, 0, 640, 480)>>>> screen.blit(img1, (imgX, imgY))<rect(0, 0, 96, 96)>>>> >>> pygame.display.flip()>>> pygame.quit();

Does yrs look like this? Post the result if it doesn't.

This way you can see what each line of the code does. IDLE basically will interpret each line of code you give it, kinda like stepping thru a program with a debugger.

Pay special attention to the line pygame.init() when you type it in to IDLE. If you receive
..., line 2, in <module>    pygame.init()AttributeError: 'module' object has no attribute 'init'

then that is troubling. It might mean that things are not setup correctly for you. Also, what operating system are you using? Is yr processor 32 or 64 bit?

##### Share on other sites
This is what I did real quick. BTW I am running off of a 32 bit OS. Windows XP. OS X should be 64 bit I think. Since whenever the hell I get this up and running I'd like this build to actually run well in modern macs if there really is going to be a crap load of issues with mac os 9.2 and GameSprockets.

>>> import pygame, sys, os>>> >>> from pygame.locals import *>>> pygame.init()(6, 0)>>> screen = pygame.display.set_mode((640, 480))>>> pygame.display.set_caption("Display an image")>>> background = pygame.Surface(screen.get_size())>>> background.fill((96, 96, 0))<rect(0, 0, 640, 480)>>>> sky6 = pygame.image.load("sky6.png").convert()Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    sky6 = pygame.image.load("sky6.png").convert()error: Couldn't open sky6.png>>>

I guess I could give copy and pasting another shot. If this doesn't work I don't know what the hell I'm suppose to do about making a pygame app.

##### Share on other sites
I don't have a mac OS so unfortunately I can't help out there, but I know windows vista might give some problems; that's the reason I asked. Maybe gives similar problems, but I know people use pygame on mac no problem....

Based on the output you posted, it appears that pygame initialized and created a window no problem, but the image did not load. Are you SURE it is in the same directory as the .py application you made?

>>> import pygame, sys, os>>> pygame.init()(6, 0)>>> from pygame.locals import *>>> img0 = pygame.image.load("0.png").convert() #error: I did not init a video modeTraceback (most recent call last):  File "<pyshell#3>", line 1, in <module>    img0 = pygame.image.load("0.png").convert()error: No video mode has been set>>> >>> screen = pygame.display.set_mode((640, 480)) # init video mode>>> img0 = pygame.image.load("0.png").convert() # image loads since i have a file called 0.png in the same directory as my .py file.>>> imgERROR = pygame.image.load("x.png").convert() # same error that you posted, this x.png file does not exist in the directory as my .py file.Traceback (most recent call last):  File "<pyshell#7>", line 1, in <module>    imgERROR = pygame.image.load("x.png").convert()error: Couldn't open x.png

edit:
Quote:
 If this doesn't work I don't know what the hell I'm suppose to do about making a pygame app.

Don't worry; you'll eventually get it to work. Sometimes it's just getting used to the language/api whatever.

##### Share on other sites
The code I previously posted was running their when I opened the .py file that was in the same folder as the .png file. I tried it with it's original name and with renaming it img0.png and it doesn't work.

##### Share on other sites
Probably it doesn't work from the IDLE shell like that because the shell is not running in the directory that your png file is in.

##### Share on other sites
Quote:
 Original post by KylotanProbably it doesn't work from the IDLE shell like that because the shell is not running in the directory that your png file is in.

Good point. I neglected to mention that when I opened the IDLE shell I right clicked on the correct .py file in its own directory, along with the pertinent image files. By right clicking on the .py file, the working directory must default to where the .py file resides. I then had the .py file side by side with the IDLE window and copy-n-pasted the lines from the script file into the IDLE prompt.
Quote:
 Original post by UnknownforestI tried it with it's original name and with renaming it img0.png and it doesn't work.

It doesn't matter what you name the file; what matters is that you refer to the file's correct name in the .py file, which is whatever you named it.

##### Share on other sites
Quote:
 Original post by KylotanProbably it doesn't work from the IDLE shell like that because the shell is not running in the directory that your png file is in.

So you saying that I should put those images in the folder python is? Or make a different folder to put them in and the .py file as well? Again, the .py file with the same code is in the same folder as the images.

The funny thing about this is I can draw a picture that doesn't fill the screen but I can't move it around nor make it quit even though I did write it as...

""" moveWalk1.py    draw an image on the screen """import pygame, syspygame.init()def main():    screen = pygame.display.set_mode((640, 480))    pygame.display.set_caption("Display an image")    background = pygame.Surface(screen.get_size())    background = background.convert()    background.fill((255, 255, 0))    walk1 = pygame.image.load("walk1.png")    walk1 = walk1.convert()    clock = pygame.time.Clock()    keepGoing = True    while keepGoing:        clock.tick(30)        for event in pygame.event.get():            if event.type == pygame.QUIT:                keepGoing = False        screen.blit(background, (0, 0))        screen.blit(walk1, (60, 60))        pygame.display.flip()if __name__ == "__main__":    main()def GetInput():    key = pygame.key.get_pressed()    for event in pygame.event.get():        if event.type == pygame.QUIT or key[K_ESCAPE]:            pygame.quit();            sys.exit()

Again the image and py file are in the same folder.

[Edited by - Unknownforest on November 14, 2009 9:44:22 PM]

##### Share on other sites
If you're not sure if your program can find the right files, use absolute paths. If that makes things work, you'll know your problem has to do with the location of your files. If things still don't work, your problem lies elsewhere. Alternately, you can check the current working directory with os.getcwd() - if that's a different folder than where your images are in, there's something wrong.

As for your code, why are you creating a background image that's solid green? Surely a 'screen.fill((255, 255, 0))' before any other drawing call would be sufficient - and it would save you some memory.

As for moving or quitting, I don't see any code that takes care of moving, and your escape-key handling function isn't called from anywhere, so it's never executed.

##### Share on other sites
Quote:
 Original post by Captain PIf you're not sure if your program can find the right files, use absolute paths.

How do I do that?

##### Share on other sites
You specify your path as "c:\exact\path\to\file\filename.png" where all of the folders I specified are replaced by the actual folder path to the file.

An absolute path is simply one that leaves no confusion, it is the absolute path on the current machine to the file.

##### Share on other sites
Quote:
 Original post by dclydeAn absolute path is simply one that leaves no confusion, it is the absolute path on the current machine to the file.

Could you give me an example of how should I type that?

##### Share on other sites
Umm...

"c:\exact\path\to\file\filename.png"

Actually, in python you have to escape all backslashes so

"c:\\exact\\path\\to\\file\\filename.png"

or

"c:/exact/path/to/file/filename.png"

##### Share on other sites
For sure that's for the 1st line of code right?

##### Share on other sites
I am not sure I follow. In all of your examples the first line of code is an import call. Certainly a full path to the image would not be a part of the import line.

The full path to the image would replace a partial path to the image, which in your last example would be "walk1.png" which you would replace the full path.

In otherwords

becomes something like (but not identical because I dont know the actual path)

Please note, this isnt the best way to program a game, far from it. This was simply suggested by someone to use this method to determine if the problem was in finding the file or not via the relative path that you had provided. I have not actually been following the entire thread, I simply saw you asking how to specify a full path and am answering it.

##### Share on other sites
I took break from programming. But am I better off using the latest version of pygame and python instead of the 2.5.2?

##### Share on other sites
Like I said I'm using the version of pygame that works with python. At the moment I feel like just giving up. I want to make a program that displays background and sprites, and move the sprite around and scroll to other backgrounds. But it looks like I'm going nowhere. I feel like I'm better off using gamemaker.