Today!, I'm trying to create an image viewer app using tkinter, the code I've written seems to get the error _tkinter.TclError: couldn't recognize data in image file "system_drive/boat.jpg"
. But besides that, to my knowledge there shouldn't be a reason why I am getting this error, the file boat.jpg
exists in the folder system_drive
and I've not made any syntactical errors either, Thanks for the help!
Code:
from tkinter import *
import os
tk = Tk()
image_list = []
for file in os.listdir(os.getcwd()):
if file.endswith(".png") or file.endswith(".jpg"):
image_list.append(PhotoImage(file))
file_name = Entry(tk, width=20,font=("Helvetica", 20))
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
def click_show_img(x):
global file_name
global image_list
print("opening system_drive/{0}".format(file_name.get()))
img = PhotoImage(file="system_drive/{0}".format(file_name.get()))
canvas.create_image(60,60, anchor=NW, image=img)
tk.bind("<Return>", click_show_img)
file_name.pack()
tk.mainloop()
Screenshots:
How the window looks like:
How it should look like:
CodePudding user response:
Tkinter doesn't support jpeg as an image format. If you want to display a .jpg file you will need to use Pillow or some other library to open it up.
From the official documentation of tk:
At present, only PNG, GIF and PPM/PGM formats are supported
This is why tkinter says it doesn't recognize the data. It has nothing to do with the path, and everything to do with the format of the data in the file. ) or some other library to open it up.
From the official documentation of tk:
At present, only PNG, GIF and PPM/PGM formats are supported
This is why tkinter says it doesn't recognize the data. It has nothing to do with the path, and everything to do with the format of the data in the file.
You also have another problem. If you don't save a reference to the image, python's garbage collector will remove the image data when the function returns. It appears you already have a global array that has the images, so I don't understand why you're creating new images.
img = PhotoImage(file="system_drive/{0}".format(file_name.get()))
image_list.append(img)
See Why does Tkinter image not show up if created in a function? for more information.
The third problem at the start of your code is that you must pass the filename to PhotoImage
as the value of the file
attribute rather than a positional argument. The first positional argument is treated as a name, not a path.
image_list.append(PhotoImage(file=file))
CodePudding user response:
You need Pillow library to open the image and display it on tkinter window.
from PIL import Image, ImageTk
Change your click_show_img function to this:
def click_show_img(x):
global file_name
global image_list
print("opening system_drive/{0}".format(file_name.get()))
img = Image.open("opening system_drive/{0}".format(file_name.get()))
img = ImageTk.PhotoImage(img)
canvas.create_image(60, 60, anchor=NW, image=img)