Cannot construct tkinter.PhotoImage from PIL Image - python

I try to show a image in a label when I push a button, but the image are too large and I have tried to resize the image. I have created this function:
def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width, height), Image.ANTIALIAS)
return im2
To show the image I have created this function:
def show_image():
label_originalimage ['image'] = image_tk
And the button with the command=show_image:
filename = 'bild_1.jpg'
image_resize = image_resize(filename)
image_tk = PhotoImage(image_resize)
button_open = Button(frame_open, text='Open Image', command=show_image)
I get only this:
TypeError : __str__ returned non-string (type instance)

The PhotoImage class from tkinter takes a filename as an argument, and as it cannot convert the image into a string, it complains. Instead, use the PhotoImage class from the PIL.ImageTk module. This works for me:
from tkinter import *
from PIL import ImageTk, Image
def image_resize(imageFile):
width = 500
height = 300
image = Image.open(imageFile)
im2 = image.resize((width,height), Image.ANTIALIAS)
return im2
def show_image():
label_originalimage ['image'] = image_tk
root = Tk()
filename = './Pictures/Space/AP923487321702.jpg'
image_resize = image_resize(filename)
image_tk = ImageTk.PhotoImage(image_resize)
label_originalimage = Label(root)
label_originalimage.pack()
button_open = Button(root, text='Open Image', command=show_image)
button_open.pack()
root.mainloop()
Notice the change from image_tk = PhotoImage(image_resize) to image_tk = ImageTk.PhotoImage(image_resize).

I had the same problem when I try to construct a canvas image item for
tkinter from a tkinter PhotoImage. The latter was constructed from some
image data in memory (in my case an opencv image). The same exception
occurs if I simply try to convert the PhotoImage to a string.
I guess there is a bug in the conversion method __str__ of the PhotoImage,
making it simply returns the image source. If constructed from a file name
(see below) this works fine. If constructed from some image data, this is not
of type string and yields an exception.
Unfortunately, using the compatible PhotoImage from PIL's
ImageTk module like matsjoyce suggested didn't help me either because I experienced an even worse problem, probably a platform or library version dependent bug (I used OS X 10.11.6, python 3.5, tkinter 8.6, PIL 1.1.7): Now the python script crashed at the construction of the canvas image item with a "Bus Error".
The only workaround I am aware of was to store the image data into a temporary file and use a tkinter PhotoImage constructed from that file name. (Trying the same with the PIL PhotoImage still crashes.)
#!/usr/bin/env python3
import tkinter
import tempfile
import cv2
def opencv2photoimg(opencv_img):
"""Convert OpenCV (numpy) image to tkinter photo image."""
# ugly workaround: store as file & load file, because direct
# construction leads to a crash on my platform
tmpfile = tempfile.NamedTemporaryFile(suffix='.png', delete=True)
# ^^^ I am using PNGs only, you might want to use another suffix
cv2.imwrite(tmpfile.name, opencv_img)
return tkinter.PhotoImage(file=tmpfile.name)
# load image
img = cv2.imread('test.png')
# do something w/ the image ...
# setup tk window w/ canvas containing an image
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=img.shape[1], height=img.shape[0])
canvas.pack()
# keep reference to PhotoImage to avoid it being garbage collected
# (well known tkinter bug for canvas image items)
photo_img = opencv2photoimg(img)
# create a canvas item
img_item = canvas.create_image(0, 0, anchor=tkinter.NW, image=photo_img)
# display the window
tkinter.mainloop()
I do not think it's elegant, but it works.

Yes it works, but yeeeucchh - what I way to have to do it.
Surely there is a better way.
Here is my test code I got to starting from here....
import tkinter
from PIL import Image
import numpy
import time
import io
#python2 version (original) -> 120fps
#full physical file io and new image each cycle -> 130fps
#reuse PIL Image instead of create new each time -> 160fps
class mainWindow():
times=1
timestart=time.clock()
data=numpy.array(numpy.random.random((400,500))*100,dtype=int)
theimage = Image.frombytes('L', (data.shape[1],data.shape[0]),data.astype('b').tostring())
def __init__(self):
self.root = tkinter.Tk()
self.frame = tkinter.Frame(self.root, width=500, height=400)
self.frame.pack()
self.canvas = tkinter.Canvas(self.frame, width=500,height=400)
self.canvas.place(x=-2,y=-2)
self.root.after(0,self.start) # INCREASE THE 0 TO SLOW IT DOWN
self.root.mainloop()
def start(self):
global data
global theimage
self.theimage.frombytes(self.data.astype('b').tobytes())
self.theimage.save('work.pgm')
self.photo = tkinter.PhotoImage(file='work.pgm')
self.canvas.create_image(0,0,image=self.photo,anchor=tkinter.NW)
self.root.update()
self.times+=1
if self.times%33==0:
print("%.02f FPS"%(self.times/(time.clock()-self.timestart)))
self.root.after(10,self.start)
self.data=numpy.roll(self.data,-1,1)
if __name__ == '__main__':
x=mainWindow()

Here it is: I found that the input data to photoimage can be a byte array that looks like a ppm file, although it only appears to work on a subset of legal ppm (e.g. 16 bit values don't work)
So for future reference.......
import tkinter
import numpy
import time
#python2 version (original) -> 120fps
#full physical file io and new image each cycle -> 130fps
#reuse PIL Image instead of create new each time -> 160fps
#and... direct image into tkinter using ppm byte array -> 240 fps
class mainWindow():
times=1
timestart=time.clock()
data=numpy.array(numpy.random.random((400,500))*900,dtype=numpy.uint16)
def __init__(self):
self.root = tkinter.Tk()
self.frame = tkinter.Frame(self.root, width=500, height=400)
self.frame.pack()
self.canvas = tkinter.Canvas(self.frame, width=500,height=400)
self.canvas.place(x=-2,y=-2)
xdata = b'P5 500 400 255 ' + self.data.tobytes()
self.photo = tkinter.PhotoImage(width=500, height=400, data=xdata, format='PPM')
self.imid = self.canvas.create_image(0,0,image=self.photo,anchor=tkinter.NW)
self.root.after(1,self.start) # INCREASE THE 0 TO SLOW IT DOWN
self.root.mainloop()
def start(self):
global data
xdata = b'P5 500 400 255 ' + numpy.clip(self.data,0,255).tobytes()
self.photo = tkinter.PhotoImage(width=500, height=400, data=xdata, format='PPM')
if True:
self.canvas.itemconfig(self.imid, image = self.photo)
else:
self.canvas.delete(self.imid)
self.imid = self.canvas.create_image(0,0,image=self.photo,anchor=tkinter.NW)
self.times+=1
if self.times%33==0:
print("%.02f FPS"%(self.times/(time.clock()-self.timestart)))
self.root.update()
self.root.after(0,self.start)
self.data=numpy.roll(self.data,-1,1)
if __name__ == '__main__':
x=mainWindow()

Related

I am getting an AttributeError when I try to resize an image I have inserted to a Tkinter window

I am trying to resize an image I inserted in my Tkinter window, but keep receiving this error message: "AttributeError: 'PhotoImage' object has no attribute 'resize'"
This is my code to resize the image:
self.path = 'S:/Öffentliche Ordner/Logos/Core Solution/Logo/CoreSolution_Logo_RGB.jpg'
self.img = ImageTk.PhotoImage(Image.open(self.path))
self.resized = self.img.resize(50,50)
self.new_img = ImageTk.PhotoImage(self.resized)
self.label = Label(master, image = self.new_img)
self.label.pack()
self.Main = Frame(self.master)
How can I resolve this error? All help is welcomed and appreciated.
As in this tutorial, it looks like it is easier to import the file as an image. Then resize it, then convert it to PhotoImage. Can you give it a try ?
# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Load the image
image=Image.open('download.png')
# Resize the image in the given (width, height)
img=image.resize((450, 350))
# Conver the image in TkImage
my_img=ImageTk.PhotoImage(img)
# Display the image with label
label=Label(win, image=my_img)
label.pack()
win.mainloop()
https://www.tutorialspoint.com/resizing-images-with-imagetk-photoimage-with-tkinter
As far as I can see, the Pillow Image.PhotoImage class is meant for displaying in tkinter but does not have all the methods of the tkinter.PhotoImage class.
Easiest is to resize the Pillow.Image before converting to Pillow Image.PhotoImage.
from tkinter import *
from PIL import Image, ImageTk
master = Tk()
path = 'images/cleese.png'
img = Image.open(path)
img.thumbnail((50,50)) # Resize Pillow Image
new_img = ImageTk.PhotoImage(img) # Convert
label = Label(master, image=new_img)
label.pack()
master.mainloop()
Try this. I did not test.
path = Image.open('S:/Öffentliche Ordner/Logos/Core Solution/Logo/CoreSolution_Logo_RGB.jpg'
self.resized = path.resize{(50,50),Image.ANTIALIAS)
self.img = ImageTk.PhotoImage(self.resized)
self.label = Label(master, image = self.new_img)
self.label.pack()
self.Main = Frame(self.master)

Is it possible to provide animation on image ? - Tkinter

I'm developing a GUI in Tkinter and want to apply animation in the below GIF on the image when it appears.
Here is my code,
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
frame = Frame(root)
frame.pack()
canvas = Canvas(frame, width=300, height=300, bd=0, highlightthickness=0, relief='ridge')
canvas.pack()
background = PhotoImage(file="background.png")
canvas.create_image(300,300,image=background)
my_pic = PhotoImage(file="start000-befored.png")
frame.after(1000, lambda: (canvas.create_image(50,50,image=my_pic, anchor=NW))) #and on this image, I want to give the effect.
root.mainloop()
Instead of clicking on the play button as shown in GIF, the image should automatically appears after 1 second like this animation and stays on screen. (No closing option).
I'm not 100% sure I understood the problem, but I'll describe how to animate an image.
Tkinter does not contain functions for animating images so you'll have to write them yourself. You will have to extract all subimages, subimage duration and then build a sequencer to swap subimages on your display.
Pillow can extract image sequences. WEBP images seems to only support one frame duration whereas GIF images may have different frame duration for each subimage. I will use only the first duration for GIF images even if there is many. Pillow does not support getting frame duration from WEBP images as far as I have seen but you gan read it from the file, see WebP Container Specification.
Example implementation:
import tkinter as tk
from PIL import Image, ImageTk, ImageSequence
import itertools
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
filename = 'images/animated-nyan-cat.webp'
pil_image = Image.open(filename)
no_of_frames = pil_image.n_frames
# Get frame duration, assuming all frame durations are the same
duration = pil_image.info.get('duration', None) # None for WEBP
if duration is None:
with open(filename, 'rb') as binfile:
data = binfile.read()
pos = data.find(b'ANMF') # Extract duration for WEBP sequences
duration = int.from_bytes(data[pos+12:pos+15], byteorder='big')
# Create an infinite cycle of PIL ImageTk images for display on label
frame_list = []
for frame in ImageSequence.Iterator(pil_image):
cp = frame.copy()
frame_list.append(cp)
tkframe_list = [ImageTk.PhotoImage(image=fr) for fr in frame_list]
tkframe_sequence = itertools.cycle(tkframe_list)
tkframe_iterator = iter(tkframe_list)
def show_animation():
global after_id
after_id = root.after(duration, show_animation)
img = next(tkframe_sequence)
display.config(image=img)
def stop_animation(*event):
root.after_cancel(after_id)
def run_animation_once():
global after_id
after_id = root.after(duration, run_animation_once)
try:
img = next(tkframe_iterator)
except StopIteration:
stop_animation()
else:
display.config(image=img)
root.bind('<space>', stop_animation)
# Now you can run show_animation() or run_animation_once() at your pleasure
root.after(1000, run_animation_once)
root.mainloop()
There are libraries, like imgpy, which supports GIF animation but I have no experience in usig any such library.
Addition
The duration variable sets the animation rate. To slow the rate down just increase the duration.
The simplest way to put the animation on a canvas it simply to put the label on a canvas, see example below:
# Replace this code
root = tk.Tk()
display = tk.Label(root)
display.pack(padx=10, pady=10)
# with this code
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack(padx=10, pady=10)
display = tk.Label(canvas)
window = canvas.create_window(250, 250, anchor='center', window=display)
Then you don't have to change anything else in the program.

QRCode displaying in tkinter GUI python

I am trying to display a QR Code in a tkinter GUI, however when I execute this code:
import tkinter as tk
from PIL import Image,ImageTk
import pyqrcode
from tkinter.font import Font
import random
root=tk.Tk()
root.title("QR Lottery")
root.config(bg="white")
# Defining Fonts
TitleFont = Font(family="HEX:gon Staggered 2", size="48")
def generateQR():
num=random.randint(1,2)
if num==1:
QRCode=pyqrcode.create("You Win!")
QRCode.png("QRCode.png",scale=8)
img = Image.open('QRCode.png')
QRCodeImg = ImageTk.PhotoImage(img)
QRCodeLabel=tk.Label(image=QRCodeImg)
QRCodeLabel.grid(row=2,column=1)
else:
QRCode=pyqrcode.create("You Lose!")
QRCode.png("QRCode.png",scale=8)
img = Image.open('QRCode.png')
QRCodeImg = ImageTk.PhotoImage(img)
QRCodeLabel=tk.Label(image=QRCodeImg)
QRCodeLabel.grid(row=2,column=1)
#Labels
TitleLabel=tk.Label(text="qr lottery",bg="white",font=TitleFont)
TitleLabel.grid(row=1,column=1,columnspan=5)
ButtonQR=tk.Button(text="Generate!",bg="white",command=generateQR)
ButtonQR.grid(row=3,column=1)
root.mainloop()
The Image Label produced is a blank square. I am unsure of why this is, as I left the background color blank.
Question: The Image Label produced is a blank square. I am unsure of why this is
A:You must keep a reference to the image object in your Python program, by attaching it to another object.
Use the following:
Define your own widget QRCodeLabel by inherit from tk.Label.
Init only with parameter parent
class QRCodeLabel(tk.Label):
def __init__(self, parent, qr_data):
super().__init__(parent)
print('QRCodeLabel("{}")'.format(qr_data))
Create your QRCode with the passed qr_data and
save as PNG file.
qrcode = pyqrcode.create(qr_data)
tmp_png_file = "QRCode.png"
qrcode.png(tmp_png_file, scale=8)
Create a image object from the PNG file.
Tkinter can handle PNG image files by its own, no PIL needed.
NOTE: You have to use self.image to prevent garbage collection!
self.image = tk.PhotoImage(file=tmp_png_file)
Configure this Label with the self.image
self.configure(image=self.image)
Usage:
class App(tk.Tk):
def __init__(self):
super().__init__()
buttonQR = tk.Button(text="Generate!", bg="white", command=self.generateQR)
buttonQR.grid(row=2, column=0)
self.qr_label = None
def generateQR(self):
if self.qr_label:
self.qr_label.destroy()
self.qr_label = QRCodeLabel(self, random.choice(["You Win!", "You Lose!"]))
self.qr_label.grid(row=1, column=0)
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5

Tkinter image not showing

I made this piece of code:
from tkinter import *
from PIL import ImageTk, Image
import sys
import getnew
class startUp:
def __init__(self, master):
master.title("Tag checker")
master.resizable(False, False)
img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.bind("<Button-1>",clicka)
cercaImg.grid(row=0,column=0)
img2 = ImageTk.PhotoImage(Image.open("images/opz.png"))
opzioniImg = Label(master, image = img2)
opzioniImg.grid(row=0,column=1)
img3 = ImageTk.PhotoImage(Image.open("images/exit.png"))
esciImg = Label(master, image = img3)
esciImg.bind("<Button-1>",(master.destroy and quit))
esciImg.grid(row=0,column=2)
def clicka(event):
print('ciaooo')
x = getnew.getSchools()
print(x[0][0],x[0][1],x[0][2])
root = Tk()
st = startUp(root)
root.mainloop()
The point is to have 3 images that, when clicked, execute a function, but he images don't show up. They do appear as size and 'clickable' zone and they execute the function, but the image as it is doesn't show up.
What am I doing wrong here ?
From tkinter docs on PhotoImage:
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
The reason to do so is :
When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.
To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute.
Hence for your program:
img1 = ImageTk.PhotoImage(Image.open("images/ss.png"))
cercaImg = Label(master, image = img1)
cercaImg.image = img1 # Keep a reference
Similarly for the other images as well.

Adding a background image in python

I'm trying to add a background image to a canvas in Python. So far the code looks like this:
from Tkinter import *
from PIL import ImageTk,Image
... other stuffs
root=Tk()
canvasWidth=600
canvasHeight=400
self.canvas=Canvas(root,width=canvasWidth,height=canvasHeight)
backgroundImage=root.PhotoImage("D:\Documents\Background.png")
backgroundLabel=root.Label(parent,image=backgroundImage)
backgroundLabel.place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas.pack()
root.mainloop()
It's returning an AttributeError: PhotoImage
PhotoImage is not an attribute of the Tk() instances (root). It is a class from Tkinter.
So, you must use:
backgroundImage = PhotoImage("D:\Documents\Background.gif")
Beware also Label is a class from Tkinter...
Edit:
Unfortunately, Tkinter.PhotoImage only works with gif files (and PPM).
If you need to read png files you can use the PhotoImage (yes, same name) class in the ImageTk module from PIL.
So that, this will put your png image in the canvas:
from Tkinter import *
from PIL import ImageTk
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)
mainloop()
just change to :
image = Image.open("~~~path.png")
backgroundImage=ImageTk.PhotoImage(image)
believe me this will 100% work
from Tkinter import *
from PIL import ImageTk
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)
mainloop()
You are using root to Attribute PhotoImage this is impossible!
root is your window Tk() class so you cant Attribute it for PhotoImage because it's dosen't have it so you see AttributeError tkinter.Tk() and tkinter.PhotoImage is a different classes. and the same with tkinter.Label.
your code will not working with root.PhotoImage and root.Label.
try to PhotoImage and Label directly.
to create a Label:
backgroundlabel = Label(parent, image=img)
if use any types of png or jpg and jpeg you can't draw it with just PhotoImage you will need PIL library
pip3 install PIL
when you have it use it like:
from PIL import Image, ImageTk # import image so you can append the path and imagetk so you can convert it as PhotoImage
now get your full path image like:
C:/.../img.png
Now use it :
path = "C:/.../img.png" # Get the image full path
load = Image.open(path) # load that path
img = ImageTk.PhotoImage(load) # convert the load to PhotoImage
now you have your code work.
full code:
from Tkinter import *
from PIL import ImageTk,Image
... other stuffs
root = Tk()
canvasWidth = 600
canvasHeight = 400
self.canvas = Canvas(root,width=canvasWidth,height=canvasHeight)
path = "D:\Documents\Background.png" # Get the image full path
load = Image.open(path) # load that path
img = ImageTk.PhotoImage(load)
backgroundLabel = Label(parent,image=img)
backgroundLabel .place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas .pack()
root .mainloop()
Hope this will helpfull.

Categories