Tkinter Photo Image Issues

I am trying to run sample code and I am running into a problem where sublime says "_tkinter.TclError: couldn't recognize data in image file "C:\Users\atave\Dropbox\Python\tkinter Python Tutorial\Labels\prac.png". Can anyone tell me why? I have already set up sublime as an exception in the firewall, does it have to do with the location of the image?

import tkinter as tk
from tkinter import ttk


# create the root window
root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Label Widget Image')

# display an image label
photo = tk.PhotoImage(file="C:\\Users\\atave\\Dropbox\\Python\\tkinter Python Tutorial\\Labels\\prac.png")
image_label = ttk.Label(
    root,
    image=photo,
    padding=5
)
image_label.pack()

root.mainloop()

2 answers

  • answered 2021-11-29 05:12 suryansh_tokas

    the tk.PhotoImage doesn't work that well with .png files. I would suggest conversion to .bmp file or using PIL(Pillow) module- tk.PhotoImage(ImageTk.PhotoImage(file="C:\\Users\\atave\\Dropbox\\Python\\tkinter Python Tutorial\\Labels\\prac.png")

    The ImageTk in ImageTk.PhotoImage() is imported from PIL(from PIL import ImageTk)

  • answered 2021-11-29 11:30 Zacky2613

    Because you're trying to grab a png you can just use PhotoImage but If you wanted to you could use PIL, but just to make it clear I'll use PhotoImage

    import tkinter as tk
    from tkinter import PhotoImage #So you can use PhotoImage
    from tkinter import ttk
    import os, sys
    
    def resource_path(relative_path): # I'm guessing the image is in the same dir as the .py file so I'll use to this help everything up (you don't have to understand it exactly you just need to know it's a more reliable and quicker way to get files in the same dir
        try:
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
    
        return os.path.join(base_path, relative_path)
    
    # create the root window
    root = tk.Tk()
    root.geometry('300x200')
    root.resizable(False, False)
    root.title('Label Widget Image')
    
    # display an image label
    photo = PhotoImage(file=resource_path("prac.png")) # You don't need to use tk. for PhotoImage.
    image_label = ttk.Label(root, image=photo, padding=5)
    image_label.pack()
    
    root.mainloop()
    

    Hope this helped.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum