如果使用 pyinstaller 将两者一起编译成 .exe 文件,如何从 python 文件访问文件夹中的 .png 文件
当我使用 Pyinstaller 将所需的文件夹和 Python 程序编译为可执行文件时,我使用了 datas = [("C:Users/Snoxzy/project/data", "data")],... 行在 .spec 文件中将“data”文件夹包含到可执行文件中,该文件夹也可以作为 pyinstaller 在编译期间创建的捆绑包中的“data”进行访问。我的 Python 程序引用了 'C:Users/Snoxzy/project/data'
文件夹中的 .png 文件,如果我稍后删除该 .png 文件,该文件将不起作用。如果我能够在 pyinstaller 创建的捆绑包中引用新创建的 'C:Users/Snoxzy/project/data'
'data' 文件夹实例,我可以稍后删除原始 .png 文件和可执行文件仍在工作,因为我引用直接集成到可执行文件中的“数据”文件夹中的 .png 文件,但我不知道该怎么做。更准确地说,我引用 .png 文件的代码部分是: field = ImageTk.PhotoImage(Image.open('C:Users/Snoxzy/project/data/other/field.png'))
。我应该使用这个 'C:Users/Snoxzy/project/data/other/field.png'
来访问捆绑文件夹“data”?
When I was compiling the desired folder and Python program into an executable using Pyinstaller I used datas = [("C:Users/Snoxzy/project/data", "data")],...
line in .spec file to include 'data' folder into executable that would also be accessible as 'data' in bundle that pyinstaller would create during compilation. My Python program references a .png file from 'C:Users/Snoxzy/project/data'
folder and that won't work if I later delete that .png file. If I was able to reference the newly created 'data' folder instance of 'C:Users/Snoxzy/project/data'
in bundle that pyinstaller created I could later delete the original .png file and executable should still be working because I am referencing .png file from a 'data' folder that is integrated directly into executable, but I don't know how to do that. More precisley, the part of code where I refrence .png file is: field = ImageTk.PhotoImage(Image.open('C:Users/Snoxzy/project/data/other/field.png'))
. What should I use insted of this 'C:Users/Snoxzy/project/data/other/field.png'
to access bundle folder 'data'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 sys.executable 在可执行文件中查找 python.exe 的路径。然后使用 os 模块构建 .png 的路径。如果您的数据文件夹与 python.exe 位于同一目录中,则此示例将起作用。
You can use sys.executable to find the path to python.exe in your executable. Then use os module to build out the path to your .png. This example will work if you have your data folder in the same dir as python.exe.