所以我用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')],
但是所有这些都会产生相同的错误。有什么建议?
答案 0 :(得分:1)
我认为问题是,您没有对图像保持引用。 看看this link for an explanation。
要添加永久引用,只需添加一行,例如
canvas1.im = image
canvas.create_image
docs确实提到了这一点
“图像对象。它应该是PhotoImage或BitmapImage,或者是兼容的对象(例如PIL PhotoImage)。应用程序必须保留对图像对象的引用”,但很容易忽视这一点!
我也不认为这是特定的Pyinstaller问题。您将图像添加到spec文件中的datas
的方法是正确的,并且应该可以正常工作。
datas = [('matrix.png','.')]
我尝试用您提供的代码片段重现您的情况,并且能够复制该错误,然后使用此方法修复它,因此希望对您有所帮助。