Python Tkinter(从函数调用)仅当函数变量“0”时才在标签中显示图片;foto";在功能上是全球化的。。。为什么会这样?

Python Tkinter(从函数调用)仅当函数变量“0”时才在标签中显示图片;foto";在功能上是全球化的。。。为什么会这样?,python,tkinter,global,Python,Tkinter,Global,我用目录中的文件名创建了一个列表框。 选择文件名会欺骗显示foto的显示函数 仅当我在show()中将foto变量设置为全局时,这才起作用 有人能向我解释为什么只有当foto变量是全局变量时它才起作用吗 (不指定全局不会出现错误,但不会显示图片) 对我来说似乎不符合逻辑,我只在show函数中使用foto变量。 谢谢 从tkinter导入* 从PIL导入ImageTk,图像 从操作系统导入listdir 从os.path导入isfile,加入 def显示(事件): 全球foto select=lb

我用目录中的文件名创建了一个列表框。 选择文件名会欺骗显示foto的显示函数

仅当我在show()中将foto变量设置为全局时,这才起作用 有人能向我解释为什么只有当foto变量是全局变量时它才起作用吗 (不指定全局不会出现错误,但不会显示图片) 对我来说似乎不符合逻辑,我只在show函数中使用foto变量。 谢谢

从tkinter导入*
从PIL导入ImageTk,图像
从操作系统导入listdir
从os.path导入isfile,加入
def显示(事件):
全球foto
select=lbox.curselection()
selected=lbox.get(选择[0])
打印(选定)
image=image.open(“images/”+选中)
image=image.resize((50,50))
foto=ImageTk.PhotoImage(图像)
label1=标签(根,图像=foto)
标签1.网格(行=0,列=1)
root=Tk()
根几何体(“”)
mypath=“/home/cor/pyprojects/images”
onlyfiles=[f表示listdir(mypath)中的f,如果isfile(join(mypath,f))]
onlyfiles.sort()
lbox=列表框(根)
lbox.insert(“结束”,*仅限文件)
lbox.bind(“,Show)
lbox.grid(行=0,列=0)
root.mainloop()

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

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

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

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

非常感谢您的新颖性,查阅并了解image=“picture.png”不会使其成为tkinter标签的属性,因此在离开函数后引用会丢失,不会忘记此项。非常感谢您的新颖性,查阅并了解image=“picture.png”不会使其成为tkinter标签的属性,因此离开函数后引用会丢失,不会忘记此项。