Tkinter PhotoImage Error: couldn't recognize data in image file - python-3.x

I am working on winows 7 and python 3.8.2. I have an error.
I wanted to upload an Image in a tkinter window. I tried importing a .gif file and I get an error as
"couldn't recognize data in image file". Though the file is in the correct path the error is happening.
Can you please help me?
Here is the Code
from tkinter import *
window = Tk()
window.title("try")
canvas = Canvas(window, height = 500, width = 500)
canvas.pack()
my_image = PhotoImage(file = "C:\\Users\\jeeva\\Pictures\\bulbon.gif")
canvas.create_image(0, 0, anchor = NW, image = my_image)
window.mainloop()
And here is the error:
Traceback (most recent call last):
File "C:\Users\jeeva\Desktop\Tanmay_new\python\Codes\Not Finished\tett.py", line 6, in <module>
my_image = PhotoImage(file = "C:\\Users\\jeeva\\Pictures\\bulbon.gif")
File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 4061, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\jeeva\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 4006, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:\Users\jeeva\Pictures\bulbon.gif"
Thank you,
Regards,
Tanmay

Related

How to fix AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?

I am trying to create a pptx or powerpoint file using python-pptx and reading the image using python wand library but getting error like AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Note: All the files are in same folder starts with 'watermarked_'
from io import FileIO
import os
from wand.image import Image
from pptx.util import Inches
from pptx import Presentation
def create_slide()->FileIO:
# Creating presentation object
root = Presentation()
for file in os.listdir():
if file.startswith('watermarked_'):
# Creating slide layout
first_slide_layout = root.slide_layouts[1]
slide = root.slides.add_slide(first_slide_layout)
shapes = slide.shapes
#Adding title or heading to the slide
title_shape = shapes.title
title_shape.text = f" Created By python-pptx for Watermarking "
#Adding sub-title with border to the slide
body_shape = shapes.placeholders[1]
tf = body_shape.text_frame
tf.text = f"This is a watermarked image of {file}"
with Image(filename = file) as watermarked_image:
#Maintianing the aspect ratio of the image
width, height = watermarked_image.size
ratio = height/width
new_width = width / 2
new_height = int(new_width * ratio)
watermarked_image.resize(int(new_width), new_height)
# Add the watermarked image to the slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
root.save("Output.pptx")
create_slide()
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
quantum#MacBook-Air image % python -u "/Users/quantum/Desktop/image/project.py"
Traceback (most recent call last):
File "/Users/quantum/Desktop/image/project.py", line 60, in <module>
create_slide()
File "/Users/quantum/Desktop/image/project.py", line 57, in create_slide
slide.shapes.add_picture(watermarked_image ,Inches(1), Inches(3))
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/shapes/shapetree.py", line 332, in add_picture
image_part, rId = self.part.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/slide.py", line 39, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 36, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/package.py", line 151, in get_or_add_image_part
image = Image.from_file(image_file)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pptx/parts/image.py", line 168, in from_file
if callable(getattr(image_file, "seek")):
AttributeError: 'Image' object has no attribute 'seek'. Did you mean: 'seed'?
Any frequent help will be much appreciated
A wand.image.Image object is not a valid argument for Shapes.add_picture(). The first argument to that call needs to be the str path to an image file or a file-like object containing an image.
I suppose that means you'll need to save the modified image as a JPG or PNG or whatever and then provide the filename. You could also save it to a BytesIO object and pass that to .add_picture() as that would count as a file-like object and not require using the filesystem.

Python _tkinter.TclError: bad screen distance "0.5" using Turtle module

I'm a turtle's beginner and I wrote a little program (file.py) who draws something.
But when I call the file with an import statement from another file (theotherfile.py. Note that it use tkinter), I have this error :
Traceback (most recent call last):
File "C:\Users\jeandubois\Documents\GitHub\myproject\theotherfile.py", line 443, in <module>
import theotherfile
File "C:\Users\jeandubois\Documents\GitHub\myproject\file.py", line 10, in <module>
turtle1 = turtle.Turtle()
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 3813, in __init__
Turtle._screen = Screen()
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 3663, in Screen
Turtle._screen = _Screen()
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 3689, in __init__
self._root.setupcanvas(width, height, canvwidth, canvheight)
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 438, in setupcanvas
self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight)
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\turtle.py", line 343, in __init__
self._canvas = TK.Canvas(master, width=width, height=height,
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2685, in __init__
Widget.__init__(self, master, 'canvas', cnf, kw)
File "C:\Users\jeandubois\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 2569, in __init__
self.tk.call(
_tkinter.TclError: bad screen distance "0.5"
My code :
# file.py
import tkinter
root = tkinter.Tk()
[some awesome code]
root.mainloop()
# when closing root:
import theotherfile
# theotherfile.py
import turtle
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtle3 = turtle.Turtle()
turtle1.speed(100)
turtle2.speed(100)
turtle3.speed(100)
turtle1.width(5)
turtle2.width(5)
turtle3.width(5)
turtle1.color(choice(colors))
turtle2.color(choice(colors))
turtle3.color(choice(colors))
turtle1.up()
turtle2.up()
turtle3.up()
turtle1.goto(-100, -100)
turtle2.goto(0, -100)
turtle3.goto(-50, -13.4)
turtle1.down()
turtle2.down()
turtle3.down()
a = 100
for loop in range(2):
for loop2 in range(3):
turtle1.forward(a)
turtle1.left(120)
turtle2.forward(a)
turtle2.left(120)
turtle3.forward(a)
turtle3.left(120)
turtle1.color(choice(colors))
turtle2.color(choice(colors))
turtle3.color(choice(colors))
a = 50
turtle1.forward(50)
turtle2.forward(50)
turtle3.forward(50)
for loop in range(5):
turtle1.forward(a)
turtle1.left(120)
turtle2.forward(a)
turtle2.left(120)
turtle3.forward(a)
turtle3.left(120)
turtle1.color(choice(colors))
turtle2.color(choice(colors))
turtle3.color(choice(colors))
turtle1.right(60)
turtle2.right(60)
turtle3.right(60)
turtle1.forward(50)
turtle2.forward(50)
turtle3.forward(50)
turtle1.up()
turtle2.up()
turtle3.up()
turtle1.hideturtle()
turtle2.hideturtle()
turtle3.hideturtle()
turtle.mainloop()
I use Python 3.9.0 .
Can someone help me please ?

Ttk style layout not found how to fix?

I am making my own custom Menubar.My work is in process but i recently came across one confusion.
Here is my code:-
from tkinter import *
from tkinter.ttk import Style,Frame as fp
class menu():
def __init__(self,parent,bg="#ffffcc"):
self.parent = parent
self.bg = bg
#this is a image in base 64 encoded format
borderImageData='''
iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAABmJLR0QA/wD/
AP+gvaeTAAACZ0lEQVRoge2aPU/TURSHn/MvpbYYKa9qQQnlTSOJRBzoYBDi
YEwcdPFD+PIFHHRxcCXxO7gxmBgXSTcxMYQEE4spoEWIvBcDBfp2HVqlxRhK
TDwtuc947vJ7cnPvGc6R/v5+KhlHO8C/YgW0sQLaWAFtqg4WxKEjJMGQaQyK
txbHpZGqmGzG7GzKyoyZfcfsOCZbeChFjaz+vAw/oq6V1K75HiERJ5v+33H/
xKnC55czF3CfYD1mxkbY+Pb7sECguUtuPQbMh5d8eksmpZL2r7jccvEGV++B
Ma+fsRzNlwOBAID3lNx+gjHm1VNiEweuqSwwWZajxCak85oEQ3wOk0my/4j7
7uD1m7ERNuY1Ux7KeozwC3x+uXI3V3AAXFXSPcjCFAtTmuFKw8xPsviRrsHc
B+MANHVS7WPuvXK0kjGz43hqaOogL3CyASC+oJrqKMQXAWoayQmI2wuY1J5q
qKOQ2gXE4+MYdGIroI0V0MYKaGMFtLEC2lgBbayANlZAGyugjRXQxgpoYwW0
sQLaWAFtrIA2DmCSCQC3RzlL6VR7AZIJ8jewtQaIv0Uz05GoPQuYrVXyAqsz
JBO0D+imKh0JhtjbYmWGvEAmbabDtPTSelk5Wimc6yNwiekw2Qz7j3hylERc
hh9S36YZ7jCkoU2GHpjtdTM5mqv8mtSnkyxFpHtQeoZIJ1n7UnbDelc1vTfl
+n1EePOcH0u5cvGyR11r/hJSeyxFzPZGmSx7SE09p3twe1j7asZGCifCcnDt
UhzaBwgOSHMnZbNuw86mWY7K3Lg5ZN2mAjkWnbiisQLaWAFtKl7gJzIjtMOb
uqQwAAAAAElFTkSuQmCC
'''
self.borderImage = PhotoImage( data=borderImageData,master=self.parent)
self.TP_style=Style()
self.TP_style.element_create("RoundedFrame",
"image", self.borderImage,
border=14, sticky="nsew")
self.TP_style.layout("RoundedFrame",
[("RoundedFrame", {"sticky": "nsew"})])
self.frame_one = fp(parent, style="RoundedFrame", padding=10,width=100,height=100)
self.frame_one.pack()
l1=Label(parent,image=self.borderImage).pack()
def popup(self,x,y,width=110,height=120):
self.width=width
self.height=height
self.app = Tk()
self.app.config(bg=self.bg)
self.app.geometry(f"{self.width}x{self.height}+{x}+{y}")
self.app.wm_attributes("-topmost",True)
self.app.overrideredirect(True)
self.app.focus_force()
#self.frame_one = fp(self.app, style="RoundedFrame", padding=10,width=100,height=100)
#self.frame_one.pack()
#l1=Label(self.app,image=self.borderImage).pack()
#self.m.pack_propagate(0)
def destroy(event):
self.app.destroy()
self.app.bind("<FocusOut>",destroy)
if __name__ == "__main__":
root = Tk()
menu = menu(root)
def evt(evt):
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
root.bind("<Button-3>",evt)
root.mainloop()
If i write style for frame like
self.frame_one = fp(parent, style="RoundedFrame", padding=10,width=100,height=100)
in the init() method every thing works fine. If same thing i write in popup methon(where i have just commented out),i got the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\mishra\P_Menu.py", line 64, in evt
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
File "C:\Users\mishra\P_Menu.py", line 51, in popup
self.frame_one = fp(self.app, style="RoundedFrame", padding=10,width=100,height=100)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py", line 740, in __init__
Widget.__init__(self, master, "ttk::frame", kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\ttk.py", line 557, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: Layout RoundedFrame not found
Same thing for Lable
l1=Label(self.app,image=self.borderImage).pack()
In the init() section everything works fine but in popup method I got following error.
Traceback (most recent call last):
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\mishra\P_Menu.py", line 64, in evt
menu.popup(evt.x_root,evt.y_root,width=200,height=400)
File "C:\Users\mishra\P_Menu.py", line 53, in popup
l1=Label(self.app,image=self.borderImage).pack()
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\mishra\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: image "pyimage1" doesn't exist
I want to know how to fix it,cause i want to know logic behind it and use in popup() method.
Any help will be appriciated.
Thank You!
Maybe it's because popup creates a new Tk instance as self.app, but the style belongs to the first Tk instance created by root = Tk(). So a child of the second Tk instance cannot recognize it. Maybe you can try changing self.app = Tk() to self.app = Toplevel() to see if it works?

PIL.UnidentifiedImageError: cannot identify image file

I'm working on GCP cloud functions and intend to write a functions which combines two images. But I', getting the following error when I invoke the function:
Traceback (most recent call last): File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 346, in run_http_function result =
_function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 217, in invoke_user_function return
call_user_function(request_or_event) File
"/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py",
line 210, in call_user_function return
self._user_function(request_or_event) File "/user_code/main.py", line
74, in execute newIntro= generateIntroImage(nameMappings['stdName'],
nameMappings['stdPicture'], nameMappings['logo'],
nameMappings['stdYear'], nameMappings['font']) File
"/user_code/main.py", line 12, in generateIntroImage
images.append(Image.open(logo)) File
"/env/local/lib/python3.7/site-packages/PIL/Image.py", line 2862, in
open "cannot identify image file %r" % (filename if filename else fp)
PIL.UnidentifiedImageError: cannot identify image file '/tmp/logo.jpg'
I have ran this function on my local machine and it works as expected but when I deploy it on GCP, it gives this error and crashes. Here's my function:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
def generateIntroImage(stdName, stdPicture, logo, year, typeFace):
images = [Image.open(x) for x in [stdPicture, logo]]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
font= ImageFont.truetype(typeFace, 70)
draw= ImageDraw.Draw(new_im)
draw.text((0, 0), stdName+"'s " +year+" Year Book", (0,0,0),font= font)
fileName= "/tmp/test.jpg"
new_im.save(fileName)
return fileName
These images are .jpg and .png files. Any idea what could be wrong?
Happened to me on Google Colab as well, apparently updating PIL version fixed the problem for me.
PIL throws error because it cannot identify the image format. Most probably the reason is that the image is corrupted and hence cannot be read (or "identified") by pillow's Image.open(). For example if you try opening the image in an IPython prompt, it would fail as well.
In [2]: from PIL import Image
In [3]: Image.open("176678612.jpg")
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-3-3f91b2f4e49a> in <module>
----> 1 Image.open("176678612.jpg")
/opt/conda/envs/swin/lib/python3.7/site-packages/PIL/Image.py in open(fp, mode, formats)
3022 warnings.warn(message)
3023 raise UnidentifiedImageError(
-> 3024 "cannot identify image file %r" % (filename if filename else fp)
3025 )
3026
UnidentifiedImageError: cannot identify image file '176678612.jpg'
And the relevant piece of code handling this check is from PIL.Image.open()
"""
exception PIL.UnidentifiedImageError: If the image cannot be opened and
identified.
"""
raise UnidentifiedImageError(
"cannot identify image file %r" % (filename if filename else fp)
So, the fix is to delete the image, or replace it with an uncorrupted version.
you need to provide a downloadable link to the image. What worked for me was click on the download image and the copy that URL.

Resize image in Tkinter

So, I need to resize an image in tkinter. Before you do anything - this is not a duplicate. I have gone through every other question on this site and none have helped me. The thing with me is - I don't wan't to save the image. I need to load the image, resize it, then display it with PhotoImage in a label. I tried to use ImageTk, but for some reason it won't work.
Here's my code with ImageTk:
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
left_nose_path_white = Image.open(r'C:\Users\User\Documents\Python stuff\Other apps\Veteris\Dog photos\Advanced\Sides\GIF\Nose\Nose (left) - White.gif')
def resize_image():
global left_nose_path_white
total_screen_width = root.winfo_screenwidth()
total_screen_height = root.winfo_screenheight()
frame_width, frame_height = left_nose_path_white.size
dog_new_width = int(frame_width / 3)
dog_new_height = int(frame_height / 3)
left_nose_path_white = left_nose_path_white.resize((dog_new_width, dog_new_height), Image.LANCZOS)
resize_image()
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
label = Label(image = left_nose_img_white)
label.pack()
root.mainloop()
This returns the error:
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
My code should find the width and height of the original image, divide it by 3, and then show it. The reason I don't want to have to save the image is because the user will open the application several times.
I'm new to using PILL/Pillow, so the answer may be obvious.
I have Pillow installed using pip.
I only have one version of Python on my computer (Python 3.7)
Full Error:
Traceback (most recent call last):
File "C:\Users\User\Documents\Python stuff\Other apps\Veteris\Scripts\Veteris_program.py", line 230, in <module>
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 95, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2779, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x000002B0A8A49950>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Thanks for the help!

Resources