Odd bugs when image processing with Pillow (in tkinter) - python

I'm having a weird problem when trying to use Pillow to display images in tkinter.
I tried originally displaying images in the default tkinter way, which worked fine for gifs:
import tkinter as tk
root = tk.Tk()
src = tk.PhotoImage(file = "C:\\Users\\Matt\\Desktop\\K8pnR.gif")
label = tk.Label(root, image = src)
label.pack()
(K8pnR is just a random gif I found on imgur)
This works great but the only problem is I want to display other file types. This lead me to Pillow, as I am working in Python 3.4. I tried to start with displaying the same file, but using Pillow:
import tkinter as tk
from PIL import Image
root = tk.Tk()
src = Image.open("C:\\Users\\Matt\\Desktop\\K8pnR.gif")
img = tk.PhotoImage(file = src)
label = tk.Label(image = img, master = root)
label.pack()
This leads to a very weird and ugly no such file or directory error:
Traceback (most recent call last):
File "C:\Users\Matt\Desktop\pil test.py", line 7, in <module>
img = tk.PhotoImage(file = src)
File "C:\Python34\lib\tkinter\__init__.py", line 3416, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python34\lib\tkinter\__init__.py", line 3372, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "<PIL.GifImagePlugin.GifImageFile image mode=P size=494x260 at 0x26A6CD0>": no such file or directory
I tried different files, different filetypes, and even reinstalling Pillow, but I still get the error.
Does anyone know what's going on here? Did I miss something totally obvious?
Edit:
When I try the suggested fix, I get this spooky error:
Traceback (most recent call last):
File "C:\Users\Matt\Desktop\pil test.py", line 6, in <module>
img = ImageTk.PhotoImage(file = src)
File "C:\Python34\lib\site-packages\PIL\ImageTk.py", line 84, in __init__
image = Image.open(kw["file"])
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2297, in open
prefix = fp.read(16)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 632, in __getattr__
raise AttributeError(name)
AttributeError: read

The problem lies in this line:
img = tk.PhotoImage(file = src)
You are using stock PhotoImage from tkinter. It is not compatible with PIL you want to use ImageTk from PIL.
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
src = Image.open("C:\\Users\\Matt\\Desktop\\K8pnR.gif")
img = ImageTk.PhotoImage(file = src)
label = tk.Label(image = img, master = root)
label.pack()
Here is documentation of stock PhotoImage class: http://effbot.org/tkinterbook/photoimage.htm , it accepts only path in constructor.

Related

Python tkinter giving me an error when I try to set me logo (GUI WINDOW)

When I try to add an image and set it as my GUI window logo it gives me these errors
Traceback (most recent call last):
File "C:\Users\Meina Jia\PycharmProjects\guwindow\main.py", line 7, in <module>
icon = PhotoImage(file='logo.jpg')
File "C:\Users\Meina Jia\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Meina Jia\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4038, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "logo.jpg"
Process finished with exit code 1
I already changed the file type using code.
from tkinter import *
window = Tk()
window.geometry("420x420")
window.title("Backrooms in A Nutshell")
icon = PhotoImage(file='logo.jpg')
window.iconphoto(True, icon)
window.mainloop()
For this, you will need the Pillow Library.
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.geometry("420x420")
window.title("Backrooms in A Nutshell")
icon = ImageTk.PhotoImage(Image.open('logo.jpg'))
window.iconphoto(True, icon)
window.mainloop()
Note: It is good practice to import a library directly:
Run
import tkinter
instead of
from tkinter import *

Opening an image using ImageTk in Pillow causing an AttributeError and RuntimeError?

I am using Pillow 7.1.2 in Python 3.8.2. I have had problems opening images using the Image.open and ImageTk.PhotoImage methods to open images to use in Tkinter programs. This is the most simple way to import images I can think of which I have written into my scratch file and I am getting an AttributeError and a RuntimeError.
from PIL import Image, ImageTk
image = Image.open("0.gif")
photo = ImageTk.PhotoImage(image)
As far as all sources I can find go, this code should work, but it doesn't. Am I missing something incredibly obvious? The errors are as follows:
Traceback (most recent call last):
File "C:/Users/cassi/AppData/Roaming/JetBrains/PyCharmEdu2020.1/scratches/scratch.py", line 4, in <module>
photo = ImageTk.PhotoImage(image)
File "C:\Users\cassi\PycharmProjects\Temp\venv\lib\site-packages\PIL\ImageTk.py", line 112, in __init__
self.__photo = tkinter.PhotoImage(**kw)
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 4061, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 3994, in __init__
raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x000001ADDF06B5E0>
Traceback (most recent call last):
File "C:\Users\cassi\PycharmProjects\Temp\venv\lib\site-packages\PIL\ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
How would I fix this? Is there something wrong with my code, or is the problem something else? Thanks!
Like this:
from tkinter import *
from PIL import Image, ImageTk
canvas = Canvas(Tk(),width=200,height=200)
canvas.pack()
image = Image.open("0.gif") # Convert to PIL image
pimage = ImageTk.PhotoImage(image) # Convert to PhotoImage
canvas.create_image(100,100,image=pimage)
tkinter raises an error when you didn't create a window(tkinter.Tk Object) before creating an ImageTk.PhotoImage Object.
Try this code, its working:
from PIL import Image, ImageTk
import tkinter
#don't use "from tkinter import *" because tkinter also has an Image object and things will get mixed up
window = tkinter.Tk()
#Now you can create an Photo Image in PIL
img = Image.open("0.gif")
tkimg = ImageTk.PhotoImage(img)
label1 = tkinter.Label(window, image = tkimg)
label1.pack()
If that also does'nt work, maybe you just downloaded a e. '0.jpg' picture and renamed it to '0.gif'.
Here's the link for converting to .gif online or here's the PIL code:
from PIL import Image
img = Image.open("0.jpg")
img.save("0.gif", "gif") # Signature of function: Image().save(name, type)

I am just trying to show an image in a GUI. What am I doing wrong?

I am trying to display an image in a GUI, and don't understand what is wrong. I keep getting this error:
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
What should my code (especially the line with my_img=...) look like?
My Code:
from tkinter import *
from PIL import ImageTk,Image
my_img = ImageTk.PhotoImage(Image.open("iu.jpeg"))
my_label = Label(image=my_img)
my_label.pack()
root = Tk()
root.title("ICON PRACTICE")
root.iconbitmap('iu.ico')
button_quit = Button(root, text = "EXIT", command=root.quit)
button_quit.pack()
root.mainloop()
The full error
Traceback (most recent call last):
File "main.py", line 4, in <module>
my_img = ImageTk.PhotoImage(Image.open("test.png"))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 112, in __init__
self.__photo = tkinter.PhotoImage(**kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python3.8/tkinter/__init__.py", line 3997, in __init__
raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image
Exception ignored in: <function PhotoImage.__del__ at 0x7f7148fadc10>
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/PIL/ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Try doing this, its probably because you create the root object after opening the image and creating the photo object.
import os
from tkinter import *
from PIL import ImageTk,Image
root= Tk()
i = Image.open("C:/path/to/the/image/directory/image.png")
photo = ImageTk.PhotoImage(i)
root.mainloop()
The Label widget will only work after root = Tk() (Tk() starts the underlying Tcl interpreter) is declared. Then, all child widgets must have root as their first parameter (e.g., Label(root, text='hi')). You started the interpreter after you tried to use it, so Python raised an exception.

Tkinter PhotoImage error "encountered an unsupported criticial chunk type "iDOT""

I am trying to show an image on screen with python and tkinter, but when I run it, it gives an error in the PhotoImage object.
This is my code:
from tkinter import *
root = Tk()
photo = PhotoImage(file="devil.png")
label = Label(root, image=photo)
label.pack()
root.mainloop()
The image file is in the same folder as the .py file.
And it gives this error:
Traceback (most recent call last):
File "C:/Users/MyUsername/PycharmProjects/GUI test/home.py", line 5, in <module>
photo = PhotoImage(file="devil.png")
File "C:\Users\MyUsername\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\MyUsername\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3498, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: encountered an unsupported criticial chunk type "iDOT"
Does anyone know how to fix this?
The chunk type of image you're using, 'iDOT', is not a registered PNG chunk. So, you should replace the image with an appropriate one.
This can help you understand what actually error is about

Problems with Images in Python's Tkinter

I have been trying to include images in my Tkinter widgets, but nothing seems to work. Here's my code:
from Tkinter import *
from PIL import Image
root = Tk()
image = Image.open('images/myimage.jpg')
root.image = image
b = Radiobutton(root, text='Image',image=image,value='I')
b.pack()
root.mainloop()
The error I get is:
Trac
eback (most recent call last):
File "C:/Users/.../loadimages.py", line 7, in <module>
b = Radiobutton(root, text='Image',image=image,value='I')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2714, in __init__
Widget.__init__(self, master, 'radiobutton', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1974, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: image "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=402x439 at 0x2A6B080>" doesn't exist
Most internet sources suggest keeping a reference to the image to avoid the garbage collector, but I don't see how I could do that more than what I have here. There are also suggestions regarding having multiple Tk instances, but I only have one.
To whoever helps, thanks in advance!
You need to convert the image you open using PIL into a PhotoImage:
from PIL import Image, ImageTk
image = Image.open("images/myimage.jpg")
photoimg = ImageTk.PhotoImage(image)
b = Radiobutton(root, image=photoimg)
See also: Photoimage API

Categories

Resources