我做了这段代码:from tkinter import *from PIL import ImageTk, Imageimport sysimport getnewclass startUp: def __init__(self, master): master.title("Tag checker") master.resizable(False, False) img1 = ImageTk.PhotoImage(Image.open("images/ss.png")) cercaImg = Label(master, image = img1) cercaImg.bind("<Button-1>",clicka) cercaImg.grid(row=0,column=0) img2 = ImageTk.PhotoImage(Image.open("images/opz.png")) opzioniImg = Label(master, image = img2) opzioniImg.grid(row=0,column=1) img3 = ImageTk.PhotoImage(Image.open("images/exit.png")) esciImg = Label(master, image = img3) esciImg.bind("<Button-1>",(master.destroy and quit)) esciImg.grid(row=0,column=2)def clicka(event): print('ciaooo') x = getnew.getSchools() print(x[0][0],x[0][1],x[0][2])root = Tk()st = startUp(root)root.mainloop()关键是有 3 个图像,当点击时,执行一个函数,但他的图像不显示。它们确实显示为大小和“可点击”区域,并且它们执行该功能,但未显示原样的图像。我在这里做错了什么?
1 回答

MM们
TA贡献1886条经验 获得超2个赞
从Tkinter的文档上PhotoImage
:
您必须在 Python 程序中保留对图像对象的引用,方法是将其存储在全局变量中,或将其附加到另一个对象。
这样做的原因是:
当 Python 对 PhotoImage 对象进行垃圾收集时(例如,当您从将图像存储在局部变量中的函数返回时),即使 Tkinter 小部件显示该图像,也会清除该图像。
为了避免这种情况,程序必须保留对图像对象的额外引用。一种简单的方法是将图像分配给小部件属性。
因此对于您的程序:
img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.image = img1 # Keep a reference
其他图像也是如此。
添加回答
举报
0/150
提交
取消