使用PyInstaller打包脚本和数据文件 - 如何使用resource_path()

时间:2014-09-18 10:29:11

标签: python python-2.7 pyinstaller

我有一个脚本从一个类中导入计算机中某个位置的tiff图像:

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打包此脚本时,图像未打包到可执行文件中。我一直在搜索,我认为解决方案是使用以下功能...

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)

我不确定在何处/如何使用此功能。我应该把它放在课堂里并像这样打电话吗?

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)

1 个答案:

答案 0 :(得分:0)

所以我仍然不知道如何使用resource_path(),但是下面的代码完成了我想要的工作:

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()