_tkinter.TclError: image "..." doesn't exist - python

I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.
This is my code:
from Tkinter import *
from PIL import Image, ImageTk
import os
window = Tk()
i = Image.open(pathToImage)
if os.path.isfile(pathToImage):
print 'image exists'
else:
print 'image does not exits'
label=Label(window, image=i)
label.pack()
window.mainloop()
It says that the image exists at the indicated path, but I keep getting this error message:
Traceback (most recent call last):
File "ImageTest.py", line 31, in <module>
label=Label(window, image=i)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist
I could not figure out how to solve this problem. Any help would be appreciated!

You should use PhotoImage instance as image value. Also, you need to keep the reference of your image.
im = Image.open(pathToImage)
ph = ImageTk.PhotoImage(im)
label = Label(window, image=ph)
label.image=ph #need to keep the reference of your image to avoid garbage collection

A quick hacky fix is to provide the PhotoImage with the correct master:
i = ImageTk.PhotoImage(pathToImage, master=window)

It seems to be an Anaconda - Spyder - Iphyton problem.
Solution is here:
_tkinter.TclError: image "pyimage" doesn't exist

Related

How i can solve this problem in Python code (TKinter, Pillow, customtkinter)

I'm trying to add an image to Customtkinter Buttom, but an error occurs
import sqlite3
from tkinter import \*
import customtkinter
from tkinter import ttk
from PIL import Image, ImageTk
customtkinter.set_appearance_mode('dark')
customtkinter.set_default_color_theme('blue')
\#Create a Ctk instance(app)
main = customtkinter.CTk()
main.geometry("400x240")
main.resizable(width=False, height=False)
\#Username Frame
username_tittle = customtkinter.CTkLabel(master=main, text='Username:').place(relx=0.2, rely= 0.3)
username_box = customtkinter.CTkEntry(master=main, width=150)
username_box.place(relx=0.43, rely=0.3)
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
but = customtkinter.CTkButton(master=main, image=python_image).pack()
this code generate the following error:
c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py:19: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use LANCZOS or Resampling.LANCZOS instead.
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
CTkButton Warning: Given image is not CTkImage but \<class 'PIL.ImageTk.PhotoImage'\>. Image can not be scaled on HighDPI displays, use CTkImage instead.
Traceback (most recent call last):
File "c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py", line 20, in \<module\>
but = customtkinter.CTkButton(master=main, image=python_image).pack()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 106, in __init__
self.\_draw()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 243, in \_draw
self.\_update_image() # set image
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 154, in \_update_image
self.\_image_label.configure(image=self.\_image.create_scaled_photo_image(self.\_get_widget_scaling(),
AttributeError: 'PhotoImage' object has no attribute 'create_scaled_photo_image'
Can anybody help me?
It looks like you are encountering an error when trying to add an image to a CTkButton widget in the customtkinter module.
The error message mentions that the given image is not a CTkImage, but a PIL.ImageTk.PhotoImage.
To fix this issue, you can try the following:
Use the CTkImage class to create an image object instead of the PIL.ImageTk.PhotoImage class. You can do this by using the CTkImage.open() method to open the image file, like this:
python_image = customtkinter.CTkImage.open('user_icon.png')
I hope this suggestion will help you.
Latest version of customtkinter accepts CTkImage only for image option of its widgets:
...
python_image = customtkinter.CTkImage(Image.open("user_icon.png"))
customtkinter.CTkButton(master=main, image=python_image).pack()
...

I was creating a image with PhotoImage and this error happened

***Error message :
Traceback (most recent call last):
File "C:/Users/gurse/Desktop/Khanda/Khanda.py", line 3, in <module>
label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))
File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4062, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4007, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\gurse\Desktop\Khanda": permission denied *****
My current code :
from tkinter import *
x = Tk()
label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))
And the backslashes turn into a Y with 2 lines across it.
That error says that it can't reach the image.
In this case, you have put only the path of the image, but the image name isn't included in it.
To resolve, you have to put also the name of the image in the path like:
r"C:\Users\gurse\Desktop\Khanda\TestImage.png
A small advice -> PhotoImage takes only a few extensions for images (ie. jpeg will occur an error)
I hope that I've been clear ;)
EDIT:
The user acw1668 isn't wrong: you have to use the method mainloop() to show the window with the widgets
According to the information in the traceback, "C:\Users\gurse\Desktop\Khanda" is a directory. So trying to open a directory as a file will raise the exception.
So you need to pass a path of an image file instead, like "C:\Users\gurse\Desktop\Khanda\sample.png".
However since you pass the result of PhotoImage(...) to image option directly, the image will be garbage collected because there is no variable references it. So you need to use a variable to store the result of PhotoImage(...).
Also you need to call grid() or pack() or place() on the label otherwise it won't show up.
Finally you need to call x.mainloop() otherwise the program will exit immediately.
Below is an example code based on yours:
from tkinter import *
x = Tk()
image = PhotoImage(file="C:/Users/gurse/Desktop/sample.png")
label = Label(x, image=image)
label.pack()
x.mainloop()

Python (tkinter) error : "CRC check failed"

I'm doing a small GUI in python, and I wanna add a button with an image. So I'm following what's said here : https://www.geeksforgeeks.org/python-add-image-on-a-tkinter-button/
It gives :
downimage = PhotoImage(file = "Downloadimage.png")
Dowloadbutton = Button(window, image=downimage, font=("Source Code Pro Light", 20), bg='black', fg='lime', command=start)
Dowloadbutton.pack()
As it is said in the link. But then the magic happens :
Traceback (most recent call last):
File "Keylogger.pyw", line 28, in <module>
downimage = PhotoImage(file = "Downloadimage.png")
File "C:\Users\Elève\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Elève\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: CRC check failed
Line 28 corresponds to downimage = PhotoImage(file = "Downloadimage.png").
Everything else is packed and appear, but my button doesn't and gives me that error.
I don't know what it means, when I try to search it on internet, a lot of non-tkinter-related results appear, it seems to be not a common but still known error.
(I'm using the last version of both python and tkinter)
If you can help me, thank you really much ! Have a nice day ;)
In png format,CRC code is here.
(An example png image)
It was encrypted(CRC32) by image chunk[0].It is a little hard for me to express that.
But the cause of your problem is the width and height of image is incorrect(mostly).Your image size has been revised.
In fact,if you put your image in linux,the image couldn't be opened normally.In windows default image viewer,system will ignore CRC checksum error,and you could open it.
How to solve your problem?
Revise this image bytes.
Use a new,correct image.

how to display HSV image - tkinter, python 2.7

I'm converting an RGB image to HSV, and trying to display the same in a Label. But I'm getting error.
My code snippet is:
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
imgthresh=Image.open(imgthresh)
re_hsv=imhsv.resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(windo, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
And my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "E:\python\track\guinew.py", line 215, in hsv_img
imhsv=Image.open(imgthresh)
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
So how to display the HSV image, is there any other way then what i have tried? Any suggestions are welcome!
Thanks in advance!
The error is thrown when you call Image.open(imgthresh), because Image.open expects a file-like object, but imgthresh is a Numpy array.
Try removing that line altogether.
EDIT: Here's a complete version that works (on my machine):
from PIL import Image, ImageTk
from Tkinter import Tk, Label, SOLID
import cv2
import numpy as np
img = np.array(Image.open('some-file.png'))
window = Tk()
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
re_hsv=Image.fromarray(imghsv).resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(window, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
hsv_img()
window.mainloop()
I had to rename some things, as well as add a call to Image.fromarray when you resize to 360x360.
It seems like most of the confusion stems from different numpy/PIL/OpenCV/Tkinter image formats. You might find this conversion guide useful, though it's slightly out of date.

Assigning and updating the image part of a Canvas widget in tkinter (Error)

Firstly, I am aware that there are similar solutions out there, and I have looked at all of them. None of them have worked- this is not a duplicate. My program is a hangman program that updates the image depending on how many wrong guesses the player has given. Here is my code. Feel free to edit and cut out irrelevant code. I have not because I don't understand the error. The code:
import random,time,sys
from tkinter import *
sys.path.append('C:/Users/Thornton/Desktop/Python Stuff/PyHang/images/') #defining the full path
class App:
def __init__(self,master):
frame=Frame(master)
frame.pack()
global e1,game
Label(frame,text='Guess').grid(row=2)
e1=Entry(frame)
e1.grid(row=2,column=1)
slider=Scrollbar(frame)
slider.grid(row=1,column=2)
self.game=Listbox(frame,height=3,yscrollcommand=slider.set)
self.game.grid(row=1,column=1)
slider.config(command=self.game.yview)
self.status=Canvas(frame,width=220,height=125) #creating the canvas
self.status.grid(row=0,column=1)
Button(frame,text='OK',command=self.guess).grid(row=2,column=2)
root.bind('<Return>',self.guess)
Button(frame,text="New\nGame",command=self.new_game).grid(row=1,column=0)
root.bind('<Home>',self.new_game)
self.new_game()
def guess(self,event=None):
frame=Frame()
frame.pack()
global losses
letter=e1.get().strip()
if len(letter)!=1 or letter.isdigit() or letter in self.used:
pass
else:
self.used.append(letter)
if letter in self.secret:
self.game.insert(END,"\n",'Correct!')
positions=[i for i,item in enumerate(self.secret) if item==letter]
for place in positions:
self.display[place]=letter
else:
self.game.insert(END,"\n",'Incorrect.')
self.losses+=1
self.status.image=PhotoImage(str(losses) + '.gif') #updating image
self.game.insert(END,''.join(self.display),'Used: ' + ''.join(self.used))
if self.losses==6:
self.game.insert(END,'You Lose.',"(" + ''.join(self.secret) + ")")
elif self.display==self.secret:
self.game.insert(END,'You Win!')
self.game.yview(END)
e1.delete(0,END)
def new_game(self,event=None):
frame=Frame()
frame.pack()
global game,losses,used,secret,display
self.secret=list(random.choice(open('dictionary.txt').readlines()))
del self.secret[-1]
self.losses=0
self.used=[]
self.display=['*' for letter in self.secret]
self.status.image=PhotoImage(file='0.gif') #resetting image
self.status.create_image(image=self.status.image)
e1.delete(0,END)
self.game.delete(0,END)
self.game.insert(END,''.join(self.display))
root = Tk()
root.title('PyHang 2.0')
app = App(root)
root.mainloop()
Output:
File "C:\Users\Thornton\Desktop\Python Stuff\PyHang\pyhang2.0.py", line 72, in new_game
self.status.image=PhotoImage(file='0.gif')
File "C:\Program Files (x86)\Python\lib\tkinter\__init__.py", line 3287, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files (x86)\Python\lib\tkinter\__init__.py", line 3243, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "0.gif": no such file or directory
The images are in the folder images, range from 0 to 6.gif and correspond to the variable losses. All the files exist and as you can see I have defined the full path. Please be patient as I am new to tkinter.
I believe you may have misunderstood sys.path as it is for locating imported Python modules. It doesn't help find the GIF in PhotoImage(file='0.gif'). The error is stating the the image was not found, so you just need to use the right relative path from where you run the script (or use the absolute path to the image).
To verify this, change this:
self.status.image=PhotoImage(file='0.gif') #resetting image
to this:
self.status.image=PhotoImage(file='images/0.gif') #resetting image
Note: this assumes the script and the images directory are both in the same directory and you are running the script from within that directory.

Categories