You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python项目中如何正确配置图标文件的相对路径?

Fixing the FileNotFoundError for Your Icon Path

Hey there! I see exactly where the issue is here—let's break this down and get your icon path working properly.

The Root Cause

When you use a path starting with a leading slash like /icons/currency/USD.png, you're telling your system to look for this folder starting from the root directory of your operating system (like C:\ on Windows or / on Linux/macOS), not your project's folder. That's why it can't find the file—your icons folder lives inside your project directory, not at the system root.

The Correct Relative Paths

Since your name_of_project.py is in the root of your project (right next to the icons folder), you have two simple, working options for the relative path:

  • Just use the path without the leading slash: icons/currency/USD.png
  • Or add ./ at the start to explicitly reference the current directory (where your script lives): ./icons/currency/USD.png

Both of these will tell Python to look inside your project's root, then into icons, then currency, to find USD.png.

If you want to avoid path issues entirely—especially if you might run your script from different working directories—use Python's built-in modules to dynamically build the path. This way, the path will always be correct no matter where you execute the script.

Using os module:

import os
# Get the directory where your script is located
script_dir = os.path.dirname(__file__)
# Build the full path to your icon
icon_path = os.path.join(script_dir, "icons", "currency", "USD.png")

Using pathlib (Python 3.4+):

from pathlib import Path
# Get the parent directory of your script
script_parent = Path(__file__).parent
# Build the path using intuitive slash notation
icon_path = script_parent / "icons" / "currency" / "USD.png"

Either of these methods will reliably point to your icon file, even if you move the project or run the script from a different folder.

内容的提问来源于stack exchange,提问作者user13602281

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:27:29