Tkinter(从函数调用)在标签中显示图片仅在函数中将函数变量“ foto”设为GLOBAL时才起作用...为什么?

时间:2020-10-29 18:12:23

标签: python tkinter global

我用目录中的文件名创建了一个列表框。 选择文件名会欺骗显示功能,该功能将显示照片

仅当我在show()中将foto变量设为全局变量时,此方法才有效 任何人都可以向我解释为什么它仅在foto变量为全局变量时才起作用 (不分配全局不会给出错误,但不会显示图片) 对我来说似乎不合逻辑,我只在显示功能中使用foto变量。 谢谢

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

1 个答案:

答案 0 :(得分:0)

这是保持对图像对象的引用的众所周知的要求。最好将其设置为属性而不是全局属性:

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