pythonimagetkintertkinter-entrytkinter-label

Tkinter Not Showing image in Label


This is my code:

import tkinter as tk
win=tk.Tk()
class loadfileclass():
    filenamevar=''
    data=''
    try:
        filenamevar=tk.StringVar()
        fname=filenamevar.get()
        filenamevar.set("")
        mainfile=open(str(fname),"rb")
        data=mainfile.read()
        data=data.split("##########")
    except:
        pass

tk.Label(text='Filename: ').pack()
tk.Entry(textvariable=loadfileclass.filenamevar).pack()
tk.Button(text='Load',command=loadfileclass).pack()
data=loadfileclass.data
for i in data:
    def fun():
        global photo,data
        data.replace("##########","\n")
        fd=data.split("==========")
        photo=Tkinter.PhotoImage(file=fd[1])
        tk.Label(fd[0],image=photo).pack()
    fun()
win.mainloop()

The label wont show, not even the image or the text.

Ok here is the file content of the file whose name i typed in the input:

IMAGE

==========
(opened image in notepad and copy pasted it here)
##########
IMAGE
==========
(opened image in notepad and copy pasted it here again)
##########

how to fix it?


Solution

  • Classic image reference problem. Try like this:

    def fun():
        global photo,data
        data.replace("##########","\n")
        fd=data.split("==========")
        photo=tk.PhotoImage(file=fd[1])
        lbl = tk.Label(fd[0],image=photo)
        lbl.pack()
        lbl.img_ref = photo # keep the reference