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
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)
...to generate the path to the file:
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)