[英]FileNotFoundError in "Python Crash Course"
我一直在使用“Python Crash Course”這本書來學習 python。 我目前在第 233-234 頁,似乎無法讓程序運行。 我應該導入船的圖像,但每次我嘗試使用self.image = pygame.image.load("images/Ship.bmp")
行執行此操作時,我都會收到一條錯誤消息“FileNotFoundError: No在工作目錄中找到文件“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)
在不同的 class 中:
self.ship = Ship(self)
以下是如何根據腳本文件的位置確定圖像文件的絕對路徑。 無論當前工作目錄是什么,這樣做都會使您的代碼正常工作。
它使用pathlib
模塊中的Path
class 使事情變得非常簡單(正如我在評論中提到的那樣,不需要使用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.
我不確定您對“在不同的 class 中:”部分的含義(甚至是下面顯示的代碼片段應該完成的內容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.