Good morning, everyone,
I tried to import image logo.gif but got an error message saying the image does not exit.
Appreciate your help.
Dennis
from PIL import Image, ImageChops
from PIL.GifImagePlugin import getheader, getdata
img = Image.open("logo.gif")
img.show()
from tkinter import *
window = Tk()
imgLbl = Label( window, image = img )
TclError: image "<PIL.GifImagePlugin.GifImageFile image mode=P size=92x95 at 0x8C92B38>" doesn't exist
Please refer to this post Play Animations in GIF with Tkinter
This question seems to be a duplicate.
You'll have to first convert the image to tK compatible image by the function PhotoImage present in ImageTk class.
Related
The url to image decoding process that I got from the internet seems to be manipulating images very weirdly and discoloring them, and as I have no idea how the process works I'm not able to figure out what the problem is. if you take this url: https://cdn.w600.comps.canstockphoto.com/human-freedom-happiness-in-nature-stock-photo_csp5610464.jpg and try to open it, it will show you the original image. But if you take the code below and try to convert that into a tkinter compatible image, it produces the same thing except the everything got tinted with blue and her skirt became yellow. Can someone figure out what the issue is or provide a better method of converting images into a format readable by tkinter? Thank you!
import cv2
import urllib.request as req
import numpy as np
from tkinter import *
from PIL import Image, ImageTk
imgUrl='https://cdn.w600.comps.canstockphoto.com/human-freedom-happiness-in-nature-stock-photo_csp5610464.jpg'
image1=''
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = req.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
class ImageFrame:
def __init__(self, master):
self.master = master
master.title("Image")
#root.geometry("1920x1080")
master.config(bg="black")
master.resizable(False,False)
self.image=Label(master, image=imgma1)
self.image.pack()
root = Tk()
imgmal = Image.fromarray(url_to_image(imgUrl))
imgmal.thumbnail((600, 650))
imgma1 = ImageTk.PhotoImage(imgmal)
mainWindow = ImageFrame(root)
root.mainloop()
The image color mode of OpenCV is in BGR, so you need to convert to RGB using cv2.cvtColor():
...
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert BGR to RGB
...
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
# Function to display image
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
# gta_images = []
os.chdir("gta")
for file in glob.glob("*.jpg"):
# gta_images.append(str(file))
displayImg(file)
print(file)
# print(gta_images)
root.mainloop()
I am trying to load images from a folder called "gta" and then display those game logos on my app. Program has no error but I think its a logical error. I am new to Python I don't know maybe there is some scoping logic problem in my displayImg funcion.
Note: 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.
For more.
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
photos = []
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
photos.append(photo)#keep references!
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
for file in glob.glob("*.jpg"):
displayImg(file)
print(file)
root.mainloop()
Not sure if it will work but try using the path of the gta folder you are getting the images from, instead of its name simply - replace the name with the path.
I am trying to pass the path of an image and then opening it but i get this error for this line image = Image.open(path):
AttributeError: type object 'Image' has no attribute 'open'
from PIL import Image
from tkinter import *
class Menu:
def __init__(self,root):
self.root = root
self.root.title("Image")
self.image_entry = Entry(root)
self.image_entry.grid(row=0,column=1)
image_label = Label(root,text = "Enter the path of the image").grid(row=0)
images = Button(root,text="Show",command=lambda:[self.show(self.image_entry)]).grid(row=1,column=1)
root.mainloop()
def show(self,image_entry):
path=image_entry.get()
image = Image.open(path)
image.show()
The variable Image imported from PIL is being overwritten by the variable Image imported from Tkinter.
Possible solutions, in descending order of best-practice-ness:
Don't import things from tkinter using import *. Try importing only the names you need, for example from tkinter import Entry, Label, Button, Tk.
Choose an alias for PIL's Image that doesn't conflict with Tkinter's Image. For example, from PIL import Image as PILImage.
Switch the order of your imports so PIL's Image overwrites Tkinter's Image, instead of the other way around.
I'm building a menu with tkinter but the icons don't show.
Can you help me?
mb=Menu(w)
w.config(menu=mb)
fm=Menu(mb,tearoff=0)
om=Menu(mb,tearoff=0)
hm=Menu(mb,tearoff=0)
mb.add_cascade(label=_("File"),menu=fm)
fm.add_command(label=_("Esci"), image=PhotoImage(r"icons\exit.png"),
compound="left",command=w.destroy)
fm.iconPhotoImage = PhotoImage(r"icons\exit.png")
mb.add_cascade(label=_("Opzioni"),menu=om)
om.add_command(label=_("Impostazioni"), image=PhotoImage(r"icons\settings.png"),
compound="left", command=settings.creaFinestra)
om.add_command(label=_("Cambia lingua"), image=PhotoImage(r"icons\language.png"),
compound="left", command=settings.cambiaLingua)
mb.add_cascade(label=_("Aiuto"), menu=hm)
hm.add_command(label=_("Guida"), image=PhotoImage(r"icons\help1.png"),
compound="left",
command= lambda: webbrowser.open("https://github.com/maicol07/school_life_diary_pc/wiki"))
hm.add_command(label=_("Informazioni"), image=PhotoImage(r"icons\help.png"),
compound="left",command=info)
As explained here, for such images formats, you need to use the PIL library which converts them to Tkinter-compatible image objects:
from PIL import Image, ImageTk
image = Image.open("icons\exit.png")
photo = ImageTk.PhotoImage(image)
Then attach it to your widget:
fm.add_command(label=_("Esci"), image=photo, ...)
You need to repeat this process for each .png image you used.
I have a very simple program on Ubuntu 14.04 LTS to read and display an image using OpenCV:
import cv2 #import OpenCV
img = cv2.imread('picture.jpg') #read a picture using OpenCV
cv2.imshow('image',img) # Display the picture
cv2.waitKey(0) # wait for closing
cv2.destroyAllWindows() # Ok, destroy the window
My problem:
How can I keep reading the picture in OpenCV but display it using Tkinter ?
I ask this because I want to make an interface for my program but OpenCV is not able to do it so I need Tkinter for this. However, all the image processing I must do it on the background using OpenCV. Only displaying the results must be done using Tkinter.
EDIT:
From the answer above, I change the line:
im = Image.open('slice001.hrs').convert2byte()
To:
im=cv2.imread() # (I imported cv2)
But I got an error.
I would appreciate any hints.
You might want to take a look at this one. Here is something works for me:
import numpy as np
import cv2
import Tkinter
from PIL import Image, ImageTk
# Load an color image
img = cv2.imread('img.png')
#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tkinter.Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Tkinter.Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
For Python3 I had to modify #Ha Dang answer:
from tkinter import *
from PIL import Image, ImageTk
import cv2
import numpy as np
image_name = 'bla.jpg'
image = cv2.imread(image_name)
#Rearrang the color channel
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
Requirements were:
pip3
numpy==1.13.1
opencv-python==3.3.0.9
Pillow==4.2.1
brew
python3
tcl-tk
For me both answers above did not work but were close. The following code did the trick for me (I also want to use place instead of pack):
from PIL import ImageTk, Image
image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
image = ImageTk.PhotoImage(image=Image.fromarray(image))
label_image = Label(self.detection, image=image)
label_image.image = image
label_image.place(x=0, y=0, anchor="w")