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

PyInstaller打包含PIL模块的Python程序遇ModuleNotFoundError求助

解决PyInstaller打包含PIL的Python程序时的ModuleNotFoundError问题

以下是针对你遇到问题的具体解决步骤:

  • 先确保PIL通过pip正规安装
    如果你的PIL是手动复制到项目目录的,先删除这个本地PIL文件夹,执行以下命令重新安装:

    pip uninstall pillow -y
    pip install pillow
    

    PyInstaller对pip安装在site-packages里的包识别更准确,手动放置的包容易出现路径识别偏差。

  • 使用.spec文件精准配置(推荐)
    命令行参数灵活性有限,用spec文件能更细致控制打包过程:

    1. 生成默认spec文件:
      pyinstaller --onefile kryptocalc.py
      
    2. 打开生成的kryptocalc.spec文件,修改以下内容:
      • 在hiddenimports中添加PIL及其依赖子模块:
        hiddenimports=['PIL', 'PIL.Image', 'PIL.ImageTk'],
        
      • 在datas字段中添加PIL的实际安装路径(替换为你环境中site-packages里的PIL路径,比如C:\Python39\Lib\site-packages\PIL):
        datas=[('C:\\Python39\\Lib\\site-packages\\PIL', 'PIL')],
        
      • 确保pathex包含你的项目目录和PIL所在的site-packages目录:
        pathex=['C:\\path\\to\\your\\project', 'C:\\Python39\\Lib\\site-packages'],
        
    3. 用修改后的spec文件重新打包:
      pyinstaller kryptocalc.spec
      
  • 先测试文件夹模式打包
    若一直使用--onefile参数,先尝试不带该参数打包,排除单文件模式的临时路径问题:

    pyinstaller kryptocalc.py
    

    运行dist/kryptocalc文件夹内的exe文件,若能正常运行,说明问题出在单文件模式的路径处理上,再回到spec文件调整datas的路径逻辑。

  • 检查PyInstaller的环境一致性
    确保运行PyInstaller的Python环境与开发环境一致:

    • 若使用虚拟环境,先激活环境再执行打包命令
    • 执行where pyinstaller(Windows)或which pyinstaller(Linux/macOS),确认其指向当前环境的PyInstaller

内容的提问来源于stack exchange,提问作者Mr. korobo4ka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:19:51