Skip to content Skip to sidebar Skip to footer

Python 3.7, Tkinter, Jpg: Couldn't Recognize Data In Image File

I wanted to ask some help regarding tkinter, in python3. I can't seem to display a jpeg image file in a label using the following code: def changephoto(self): self.tmpimgpath =

Solution 1:

  1. You have to install PIL: pip install pillow.

    If pip does not successfully install pillow, you might have to try pip3 or pip3.7(use bash to see which options you have)

  2. You can open your image with ImageTk:

    import os
    import tkinter as tk
    from tkinter import filedialog
    from PIL import ImageTk
    
    def changephoto():
       root = tk.Tk()
       PictureLabel= tk.Label(root)
       PictureLabel.pack()
       tmpimgpath = filedialog.askopenfilename(initialdir=os.getcwd())
       selectedpicture= ImageTk.PhotoImage(file=tmpimgpath)
       PictureLabel.configure(image=selectedpicture)
    

Solution 2:

Solution provided by Chuck G worked. I can't tell why I initially couldn't import ImageTk, but that ended up to just work.

fromPILimportImageTk

Solution 3:

This error could possibly happen because of relative file path or non-English characters in filepath ,So i made this function which works very good in windows and with any kinds of file paths :

def loadrelimages(relativepath):
    from PIL import ImageTk, Image
    import os
    directory_path = os.path.dirname(__file__)
    file_path = os.path.join(directory_path, relativepath)
    img = ImageTk.PhotoImage(Image.open(file_path.replace('\\',"/")))  
    return img

for example load photo_2021-08-16_18-44-28.jpg which is at the same directory with this code:

from tkinter import *
import os

def loadrelimages(relativepath):
    from PIL import ImageTk, Image
    import os
    directory_path = os.path.dirname(__file__)
    file_path = os.path.join(directory_path, relativepath)
    img = ImageTk.PhotoImage(Image.open(file_path.replace('\\',"/")))  
    return img
root = Tk()

canvas = Canvas(root, width=500, height=500)
canvas.pack()


loadedimage=loadrelimages('photo_2021-08-16_18-44-28.jpg')
canvas.create_image(250, 250, image=loadedimage)

root.mainloop()


try this!!!!

Post a Comment for "Python 3.7, Tkinter, Jpg: Couldn't Recognize Data In Image File"