Search code examples
pythonimagetkinterlabelstringio

How to load a image into a label without saving to hard drive python Tkinter


I am working on a project where I have a list with a couple of StringIO in it. I want to load those into a Tkinter label but I get this error: IOError: cannot identify image file. I understand that it means it can not find the image file. But how can I display a image without saving to the hard drive?

Here is my code:

from PIL import ImageTk, Image as im
from cStringIO import StringIO
from threading import Thread
from Tkinter import *
import socket
import os

class Application(Frame):
    def __init__(self, parent):
        Frame.__init__(self,parent)
        self.pack(fill=BOTH)

        self.images = []

        self.create_Browse()

    def create_Browse(self):
        for item in self.images:
            img = ImageTk.PhotoImage(im.open(item))

            label = Label(self, image=img)
            label.image = img
            label.pack(side=TOP)

root = Tk()
root.title("None")
root.resizable(0,0)
root.geometry("650x500")
root.iconbitmap("Files/System_Files/icon.ico")

app = Application(root)

root.mainloop()

This is just a example. The self.images list will have the StringIO's in it.


Solution

  • You may need to reset your StringIO objects before creating the images:

    for item in self.images:
        item.seek(0) # set file position back to the start
        img = ImageTk.PhotoImage(Image.open(item))