Tkinter(从函数调用)仅在函数变量"foto"在函数中成为全局时才有效...这是为什么呢?



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

只有当我在show((中将foto变量设置为全局变量时,这才有效有人能向我解释为什么只有当foto变量是全局变量时它才有效吗(不分配全局不会产生错误,但不会显示图片(我只在show函数中使用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()

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

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

最新更新