」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 Pygame 中載入資源時如何修復“FileNotFoundError”?

在 Pygame 中載入資源時如何修復“FileNotFoundError”?

發佈於2024-12-23
瀏覽:567

How to Fix

使用Pygame 載入資源:解決「FileNotFoundError」

當嘗試在Pygame 中載入圖片或聲音等外部資源時,您可能會遇到“FileNotFoundError:沒有這樣的檔案或目錄”錯誤。此問題通常是由於資源檔案路徑不正確造成的,特別是當路徑相對於目前工作目錄時。

解決方案:設定工作目錄或建立絕對檔案路徑

要解決此錯誤,請確保將工作目錄設定為資源檔案所在的位置。這可以透過 os 模組來實現:

import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))

或者,您可以透過組合檔案的目錄路徑和檔案名稱來建立絕對檔案路徑:

filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
surface = pygame.image.load(filePath)

使用pathlib的替代解決方案

pathlib模組提供了另一種設定工作目錄或建立絕對檔案路徑的方法:

設定工作目錄:

import os, pathlib

os.chdir(pathlib.Path(__file__).resolve().parent)

建立絕對檔案路徑:

import pathlib

filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3