使用 PyInstaller 打包脚本和数据文件——如何使用 resource_path() [英] Packaging a script and data file using PyInstaller - how to use resource_path()
本文介绍了使用 PyInstaller 打包脚本和数据文件——如何使用 resource_path()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个脚本,它从我的计算机中的某个位置从一个类中导入一个 tiff 图像:
I have a script which imports an tiff image from a location in my computer from inside a class:
from PIL import Image, ImageTk
import Tkinter
class Window(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# More code here
self.photo = ImageTk.PhotoImage(Image.open('C:\Users\...\image\image.tif'), self)
ImageLabel = Tkinter.Label(self, image=self.photo)
ImageLabel.grid()
# More code here
当我使用 PyInstaller 打包此脚本时,图像未打包到可执行文件中.我四处搜索,我认为解决方案是使用以下功能...
When I package this script using PyInstaller the image is not packaged into the executable. I have searched around and I think the solution is to use the following function...
def resource_path(relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
...生成文件路径:
filename = 'image.tif'
filepath = resource_path(os.path.join(data_dir, filename)
我不确定在哪里/如何使用此功能.我应该把它放在类中并像这样调用它吗?
I am not sure of where/how to use this function. Should I put it inside the class and call it like this?
from PIL import Image, ImageTk
import Tkinter
class Window(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# More code here
filename = 'image.tif'
data_dir = 'C:\Users\...\image'
filepath = self.resource_path(os.path.join(data_dir, filename)
self.photo = ImageTk.PhotoImage(Image.open(filepath), self)
ImageLabel = Tkinter.Label(self, image=self.photo)
ImageLabel.grid()
# More code here
def resource_path(self, relative):
if hasattr(sys, "_MEIPASS"):
return os.path.join(sys._MEIPASS, relative)
return os.path.join(relative)
推荐答案
所以我仍然不知道如何使用 resource_path(),但以下代码完成了我想要的工作:
So I still don't know how to use resource_path(), but the following code does the job I wanted:
from PIL import Image, ImageTk
import Tkinter
class Window(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
# See if running as script or executable and get path of the script/application
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
# Join application path and relative file path
filename = 'image.tif'
pathtofile = os.path.join(application_path, filename)
self.photo = ImageTk.PhotoImage(Image.open(pathtofile, self)
ImageLabel = Tkinter.Label(self, image=self.photo)
ImageLabel.grid()
这篇关于使用 PyInstaller 打包脚本和数据文件——如何使用 resource_path()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文