Home > Blockchain >  Tkinter Photo Image Issues
Tkinter Photo Image Issues

Time:11-29

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

CodePudding user response:

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)

CodePudding user response:

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.

  • Related