用 PyInstaller 打成单文件 exe 后,源码旁边的 btn.png 不会自动出现。资源要么嵌入包内,要么和 exe 一起外置分发。

方式 A:嵌入 exe

pyinstaller -F -w --add-data "btn_screenshot.png;." your_script.py
import os, sys, cv2

def resource_path(relative_path: str) -> str:
    if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

btn = cv2.imread(resource_path("btn_screenshot.png"))

方式 B:外置资源

pyinstaller -F -w your_script.py
# 分发时保证 exe 与 btn_screenshot.png 同目录

怎么选

  • 嵌入:分发简单,exe 更大。
  • 外置:exe 更小,但要保证相对路径不被破坏。
  • Windows 的 --add-data 分隔符是 ;,Linux/macOS 是 :