2016-02-13 192 views
2

我跟隨this guide試圖在Pygame窗口中顯示一個基本的PNG圖像。我的形象是一個簡單的150×150綠球不透明度稱爲ball.png,位於同一目錄作爲我的Python腳本:Pygame PNG圖像看起來腐敗

Ball.png

然而,當我開始我的程序,出現一切的一個出問題圖像正確尺寸和位置:

enter image description here

我使用這個代碼以顯示圖像(等同於上面鏈接教程給出的代碼):

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) 

爲什麼會發生這種情況?代碼中是否存在缺陷?我曾嘗試用不同的PNG替換PNG,但這只是改變了圖像看起來很糟糕 - 圖像仍然無法正確顯示。我使用OS X 10.11 El Capitan,Python 3.5.0和Pygame 1.9.2。

+0

什麼是路徑替換的東西應該做的到底是什麼? – xXliolauXx

+0

@xXliolauXx'get_image'函數應該存儲已經根據教程加載的圖像。它似乎並不是問題,因爲如果我將函數更改爲僅返回pygame.image.load(path).convert(),問題仍然存在。 –

+2

Pygame + El Capitan已知有幾個渲染問題。當我在我的機器上運行這段代碼(Windows 10)時,一切都很正常。你可以在這裏找到更多的信息:https://bitbucket.org/pygame/pygame/issues/284/max-osx-el-capitan-using-the-deprecated如何解決它。 – DJMcMayhem

回答

4

正如@DJ McGoathem所說,Pygame已經知道El Capitan的問題,因爲SDL_image庫的版本不同; Pygame需要1.2.10版本,但El Capitan有1.2.12。這可以通過降級這個庫,我不喜歡這樣來解決(需要BREW):

  1. 複製this code到一個名爲sdl_image.rb
  2. 打開保存該文件
  3. 運行目錄內的終端文件brew remove sdl_image卸載庫
  4. 運行brew install -f sdl_image.rb的不兼容版本安裝庫的兼容版本

之後,我的程序正在渲染圖像。

+0

似乎很好的回答,問題和解決方案很好地描述。 +1 – xXliolauXx