1

i created a listbox with filenames from a directory. Selecting a filename trickers the show function which will display the foto

This does only works when i make the foto variable global in show() Can anybody explain to me why it only works when the foto variable is global (Without assigning global gives no error, but does not show the picture ) Does not seem logic to me i only use foto variable in the show function. Thanks

    from tkinter import *
    from PIL import ImageTk,Image
    from os import listdir
    from os.path import isfile, join
    
    
    def Show(event):
        global foto
        select = lbox.curselection()
        selected = lbox.get(select[0])
        print(selected)
    
        image = Image.open("images/" + selected)
        image = image.resize((50,50))
        foto = ImageTk.PhotoImage(image)
    
        label1 = Label(root, image=foto)
        label1.grid(row=0, column=1)
        
    
    root=Tk()
    root.geometry("")
    
    mypath = "/home/cor/pyprojects/images"
    onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    onlyfiles.sort()
    
    lbox = Listbox(root)
    lbox.insert("end", *onlyfiles)
    lbox.bind("<<ListboxSelect>>", Show)
    lbox.grid(row=0, column=0)


root.mainloop()
Cornelis
  • 11
  • 1

1 Answers1

0

This is the well known requirement of keeping a reference to an image object. It's much better to make it an attribute instead of a global:

def Show(event):
    select = lbox.curselection()
    selected = lbox.get(select[0])
    print(selected)

    image = Image.open("images/" + selected)
    image = image.resize((50,50))
    foto = ImageTk.PhotoImage(image)

    label1 = Label(root, image=foto)
    label1.grid(row=0, column=1)
    label1.foto = foto # keep a reference
Novel
  • 13,406
  • 2
  • 25
  • 41
  • Thanks a lot Novel , looked it up and understand that image="picture.png" does not make it an attribute of tkinter Label so reference gets lost after leaving the function Wont forget this one. – Cornelis Oct 30 '20 at 00:33