简体   繁体   中英

Tkinter image not showing

I made this piece of code:

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

The point is to have 3 images that, when clicked, execute a function, but he images don't show up. They do appear as size and 'clickable' zone and they execute the function, but the image as it is doesn't show up.

What am I doing wrong here ?

From tkinter docs on PhotoImage :

You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.

The reason to do so is :

When a PhotoImage object is garbage-collected by Python (eg when you return from a function which stored an image in a local variable), the image is cleared even if it's being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute.

Hence for your program:

img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.image = img1 # Keep a reference

Similarly for the other images as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM