2013-03-21 47 views
4

當我試圖在另一個文件夾我可以加載圖像...錯誤使用pygame.image.load()時

pygame.error:無法打開精靈/ testtile.png

我可以加載.png文件就好了,如果它們在同一個目錄中,但一旦它們在另一個文件夾中,我會得到這個錯誤。

我知道python也可以訪問那個其他文件夾,因爲我從摺疊中導入.py文件時沒有錯誤。

當我嘗試pygame.image.get_extended它返回一個0,但從同一目錄加載.png文件給我沒有問題,所以我不認爲這是什麼導致此問題。

我正在運行PyCharm,這樣的事情似乎總是給我這個IDE帶來麻煩。我甚至不認爲這是一個pygame問題。不知道該怎麼做。

文件夾結構:

腳本/ GraphicsDriver.py

精靈/ testtile.png

驅動程序試圖訪問testile.png文件

回答

3

是在精靈目錄目錄與GraphicsDriver.py?您可能會遇到PyGame圖像加載器的一些問題。它在PyGame初始化的同一目錄中查找文件。使用'os.path.join'將它指向文件的絕對路徑。

我通常在它周圍寫下我自己的小圖片加載器,因爲它提供了更多的過程靈活性。像這樣會返回圖像和矩形:

def load_image(name, colorkey = None): 
    """loads an image and converts it to pixels. raises an exception if image not found""" 
    fullname = os.path.join('data', name) 
    try: 
     image = pygame.image.load(fullname) 
    except pygame.error, message: 
     print 'Cannot load image:', name 
     raise SystemExit, message 
    image = image.convert() 
    # set the colorkey to be the color of the top left pixel 
    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() 

希望這會有所幫助。

+0

感謝您的幫助。我實現了你的方法,並將其運行爲「testtile,testtile_rect = load_image('testtile.png')」。這返回'無法打開數據\ testtile.png'和'無法加載圖像:testtile.png' – bilbs 2013-03-21 01:49:37

+0

全名= os.path.join('數據',名稱)可以改爲全名= os.path.join( '精靈',名字)爲混淆抱歉。我從我的腳本中的一個腳本中抽取了這些代碼,並將其映射到數據目錄中。 – ecline6 2013-03-21 01:59:46

+0

是的,我嘗試了幾個不同的目錄,我認爲數據是一個佔位符。不幸的是,它仍然返回相同的錯誤。 – bilbs 2013-03-21 02:08:12