首页 > 解决方案 > Python 应用程序在运行时找不到图像(.png)文件

问题描述

所以我用 tkinter GUI 构建了这个 python 应用程序。我使用 pyinstaller 将 .py 文件转换为可执行(.exe)文件,以便我可以将其发送给非技术人员使用。

当我运行代码时将这两行注释掉...

root = tk.Tk()
root.title("DOJ Pricing Analyzer")
root.resizable(False,False)
#canvas1 = tk.Canvas(root, width = 350, height = 500, bg = 'white') <-----------This line commented out
#image = ImageTk.PhotoImage( file = "matrix.png" )<--------------This line commented out
canvas1.create_image(0, 0, image = image, anchor = NW)
canvas1.create_text(185,75,fill="white",font="Impact 15 ",

应用程序在执行时完美运行(在 Windows 中以 .exe 形式),但主窗口是空白的白色画布。

问题是我需要应用程序使用 matrix.png 以便 UI 看起来很酷且不乏味。

因此,经过数小时的研究,我尝试以多种不同的方式处理 .spec 文件。我认为这可以解决问题....(我只是将 matrix.png 文件添加到数据中),然后从 Powershell 运行 pyinstaller DOJPriceAnalyzer.py --onefile

# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['DOJPriceAnalyzer.py'],
             pathex=['C:\\Users\\CV7617\\Desktop\\program'],
             binaries=[],
             datas=[('C:\\Users\\CV7617\\Desktop\\program\matrix.png','.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='DOJPriceAnalyzer',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True )

但是在运行它产生的 .exe 之后,我留下了这个错误:


Traceback (most recent call last):
  File "DOJPriceAnalyzer.py", line 16, in <module>
  File "site-packages\PIL\ImageTk.py", line 89, in __init__
  File "site-packages\PIL\ImageTk.py", line 58, in _get_image_from_kw
  File "site-packages\PIL\Image.py", line 2809, in open
FileNotFoundError: [Errno 2] No such file or directory: 'matrix.png'
[3080] Failed to execute script DOJPriceAnalyzer
Exception ignored in: <function PhotoImage.__del__ at 0x0F9F07C8>
Traceback (most recent call last):
  File "site-packages\PIL\ImageTk.py", line 118, in __del__
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

我已经尝试了很多东西的组合(此时丢失了计数),包括这个..(将 .spec 文件修改为这些,然后通过运行 pyinstaller DOJPriceAnalyzer.py --onefile 的相同动作,然后运行 ​​.exe 文件)

datas=[(matrix.png','.')],

datas=[('C:\\Users\\CV7617\\Desktop\\program','data')],

但是这些都会产生相同的错误。有什么建议么?

标签: pythonimageruntimeexepyinstaller

解决方案


我认为问题是,您没有保留对图像的引用。看看这个链接以获得解释

要添加永久引用,只需添加一行,例如

canvas1.im = image

canvas.create_image文档确实提到了这一点

“图像对象。这应该是 PhotoImage 或 BitmapImage,或兼容的对象(例如 PIL PhotoImage)。应用程序必须保留对图像对象的引用”,但很容易忽略这一点!

我也不认为这是特定的 Pyinstaller 问题。您将图像添加到datas规范文件中的方法是正确的,应该可以正常工作。

datas = [('matrix.png','.')]

我尝试使用您提供的代码片段来重现您的案例,并且我能够复制错误,然后使用此方法修复它,因此希望这对您也有帮助。


推荐阅读