Aaron Christiansen
Aaron Christiansen

Reputation: 11807

Pygame PNG image looks corrupt

I'm following this guide to try and display a basic PNG image inside a Pygame window. My image is a simple 150x150 green ball with no transparency called ball.png, located in the same directory as my Python script:

Ball.png

However, when I start my program, all that appears is a glitchy image of the correct size and location:

enter image description here

I am using this code to display the image (identical to the code given in the tutorial linked above):

import pygame
import os

_image_library = {}
def get_image(path):
        global _image_library
        image = _image_library.get(path)
        if image == None:
                canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
                image = pygame.image.load(canonicalized_path)
                _image_library[path] = image
        return image

pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
        screen.fill((255, 255, 255))
        screen.blit(get_image('ball.png'), (20, 20))
        pygame.display.flip()
        clock.tick(60)

Why would this happen? Is there a flaw in the code? I have tried replacing the PNG with different ones, but that just changes how the glitchy image looks - the image is still not displayed correctly. I'm using OS X 10.11 El Capitan, Python 3.5.0 and Pygame 1.9.2.

Upvotes: 3

Views: 824

Answers (2)

KWC
KWC

Reputation: 119

No problem when doing the source code under pygame 2.1.2, python 3.9 and macOs 12.6.1. Just find a ball.png file and it displayed. I have other pygame so far all ok.

Still the pygame_card sample app is not working which leads me to here. I suspect the requirement to access all keyboard form all apps plus this require me to dig into it further. But SDL may have update and all good for general cases.

Upvotes: 0

Aaron Christiansen
Aaron Christiansen

Reputation: 11807

As @DJ McGoathem said, Pygame has known issues with El Capitan due to differing versions of the SDL_image library; Pygame needs version 1.2.10 but El Capitan has 1.2.12. This can be solved by downgrading this library, which I did like this (requires Brew):

  1. Copy this code into a file called sdl_image.rb
  2. Open a Terminal inside the directory where you saved that file
  3. Run brew remove sdl_image to uninstall the incompatible version of the library
  4. Run brew install -f sdl_image.rb to install the compatible version of the library

After this, my program was rendering the image correctly.

Upvotes: 5

Related Questions