我一直在使用“Python Crash Course”這本書來學習 Python。我目前在第 233-234 頁,似乎無法讓程式運行。我應該匯入船舶的影像,但每次嘗試使用該行執行此操作時,self.image = pygame.image.load("images/Ship.bmp")都會收到錯誤訊息“FileNotFoundError:在作業目錄中找不到檔案'Ship.bmp'。我的作業目錄在哪里以及如何我可以把我的檔案放在那里嗎?(使用視覺學習)
class Ship:
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_Rect = ai_game.screen.get_rect()
self.image = pygame.image.load("images/Ship.bmp")
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
self.screen.blit(self.image, self.rect)
在不同的班級:
self.ship = Ship(self)
uj5u.com熱心網友回復:
以下是如何根據腳本檔案的位置確定影像檔案的絕對路徑。無論當前的作業目錄是什么,這樣做都會使您的代碼正常作業。
它使用模塊中的Path類pathlib使事情變得非常簡單(沒有必要os.path像我在評論中提到的那樣使用來做事——盡管也可以使用它來完成)。
from pathlib import Path
class Ship:
# Determine absolute path from relative path.
image_path = Path(__file__).parent / "images/Ship.bmp"
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_Rect = ai_game.screen.get_rect()
self.image = pygame.image.load(self.image_path)
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
self.screen.blit(self.image, self.rect)
print(Ship.image_path) # -> Will show absolute path to image file.
我不確定你對“在不同的類中:”部分的意思(或者甚至是下面顯示的代碼片段應該完成什么)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402862.html
標籤:
