Python (tkinter) error : "CRC check failed" - python

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.

Related

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-pptx: issue with insert_picture() function - 'sha1' AttributeError

I am trying to write a basic script to update a PowerPoint (2016) presentation, template.pptx, which contains predefined place holders for images. I am running into issues with the insert_picture() function.
As an example, the 4th slide of template.pptx contains a Picture Placeholder:
from pptx import Presentation
prs = Presentation('template.pptx')
slide4 = prs.slides[3]
for shape in slide4.placeholders:
print('%d %s' % (shape.placeholder_format.idx, shape.name))
which gives the following output
>>>
0 Title 3
10 Picture Placeholder 7
I proceed with
placeholder = slide4.placeholders[10] # idx key, not position
picture = placeholder.insert_picture('test.jpg')
Which throws the following error(s):
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 323, in insert_picture
pic = self._new_placeholder_pic(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 334, in _new_placeholder_pic
rId, desc, image_size = self._get_or_add_image(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 345, in _get_or_add_image
image_part, rId = self.part.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\parts\slide.py", line 42, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 50, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 159, in get_or_add_image_part
image_part = self._find_by_sha1(image.sha1)
File "C:\Python273\lib\site-packages\pptx\package.py", line 171, in _find_by_sha1
if image_part.sha1 == sha1:
AttributeError: 'Part' object has no attribute 'sha1'
I have seen this 'sha1' error mentioned in these forums but don't fully understand it (I am a bit of a novice).
Interestingly (frustratingly), I don't run into this issue when creating a PowerPoint from scratch (as per the example in the python-pptx 0.6.7 docs):
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1] # idx key, not position
picture = placeholder.insert_picture('test.jpg')
prs.save('new.pptx')
This runs fine, hence I am left very confused. Any help would be much appreciated. Thanks!
(Windows 7, Python 2.7.3)
I have found a possible cause for this problem! For me the problem was that the presentation contained images that were not in either jpg, png or gif. It was a tif file. For these files, theres is no sha1 and therefore the script throws an exception. Converting/deleting these files made the problem disappear!
Please tell me if that fixes it for you too.

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

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

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