Show image object

from tkinter import *
from PIL import ImageTk, Image

    #Create an image
    #img_image1 = ImageTk.PhotoImage(Image.open("myimage.jpg"))
    img_image1 = ImageTk.PhotoImage(Image.open("myimage.jpg").resize((50, 50)))        #<<<Set the desired image size (if you want your image displaed at a different size you have to resize it first like this)
    label_image1 = Label(root, image=img_image1)
    label_image1.image = img_image1               #Keep a reference to the image so its not destoyed
    label_image1.place(x=5, y=50)                #Top left corner of the image placement
Update an image
#Make the image and its label holder global
    global img_image1
    global label_image1

    #Update it to a new image:
    img_image1 = ImageTk.PhotoImage(Image.open("myimage2.jpg").resize((250, 141)))      #<<<Set the desired image size (if necessary)
    label_image1.configure(image=img_image1)

Image is blank

When you add an image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up. This is because the Tkinter/Tk interface doesn’t handle references to Image objects properly; the Tk widget will hold a reference to the internal object, but Tkinter does not. When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent…

The solution is either to make a global image object, or to make sure to keep a reference to the Tkinter object, for example by attaching it to a widget attribute:

label = Label(image=photo)
label.image = photo     #Keep a reference to the image so its not destoyed
label.pack()

Update image from a different formatted source image type

    img = ap_opencv.cv2.cvtColor(ap_opencv.annotated_frame, ap_opencv.cv2.COLOR_BGR2RGB)
    img = Image.fromarray(img)
    img = img.resize((250, 141))      #<<<Set the desired image size
    img_camera_image = ImageTk.PhotoImage(img)
    label_camera_image.configure(image=img_camera_image)
    label_camera_image.image = img_camera_image               #Keep a reference to the image so its not destoyed
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *