猿问

Tkinter 图像未显示

我做了这段代码:


from tkinter import *

from PIL import ImageTk, Image

import sys

import getnew



class 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 个图像,当点击时,执行一个函数,但他的图像不显示。它们确实显示为大小和“可点击”区域,并且它们执行该功能,但未显示原样的图像。


我在这里做错了什么?


慕妹3242003
浏览 171回答 1
1回答

MM们

从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其他图像也是如此。
随时随地看视频慕课网APP

相关分类

Python
我要回答