Reputation: 17
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 = filedialog.askopenfilename(initialdir=os.getcwd())
self.installimagepath.set(self.tmpimgpath)
self.selectedpicture = PhotoImage(file=self.installimagepath.get())
self.PictureLabel.configure(image=self.selectedpicture)
It can do png Images just fine, but when I try to load a jpg image, all I i am able to get is the following error:
_tkinter.TclError: couldn't recognize data in image file
I went through all similar questions I could find, but they all seem to answer the same thing: "from PIL import ImageTk, Image" When I try that ( for the moment, I am trying to use pillow, btw ), ImageTk doesn't seem to be available.
Any help would be greatly appreciated.
Upvotes: 2
Views: 7555
Reputation: 113
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!!!!
Upvotes: -1
Reputation: 17
Solution provided by Chuck G worked. I can't tell why I initially couldn't import ImageTk, but that ended up to just work.
from PIL import ImageTk
Upvotes: 0
Reputation: 805
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)
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)
Upvotes: 2