Unable to Load an Image from an URL at TKinter - python

My goal is to display an JPG image from an URL using tkinter python.
This is the stackoverflow link that I used as a reference. But when I try to run the code, I have received a bunch of error such as:
KeyError: b'R0l.......
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Does anyone have the solution to this?
This is the code:
import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
import base64
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
photo = ImageTk.PhotoImage(b64_data)
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()

The first error is not specifying the data parameter within ImageTk.PhotoImage(data=b64_data). However, I'm unsure why PhotoImage is unable to read base64 data.
A workaround would be to use BytesIO from the io module. You can pass in the raw data you read from the image into a BytesIO, open it in Image and then pass that into PhotoImage.
I found the code for opening the image from here.
import tkinter as tk
from PIL import Image, ImageTk
from urllib2 import urlopen
from io import BytesIO
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
photo = ImageTk.PhotoImage(im)
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()
If anybody has a better answer as to why the encoding fails, it would be a more appropriate answer to this question.

Very similar but easier than Hobbes' answer, you can directly use the data parameter in the ImageTk.PhotoImage constructor:
import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
root = tk.Tk()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
photo = ImageTk.PhotoImage(data=raw_data) # <-----
label = tk.Label(image=photo)
label.image = photo
label.pack()
root.mainloop()

Related

Imported libaries causing overlap

I'm trying to make an interface using tkxui and tkinter for the modules it doesn't cover (Label, anchors etc)
from urllib.request import urlopen
from PIL import Image, ImageTk
from io import BytesIO
from tkinter import *
import tkxui
win = tkxui.Tk(display=tkxui.FRAMELESS, defaultBorder=True)
win.geometry("700x400")
win.title("Window Title")
win.minsize(700, 400)
win.center()
URL = "http://www.universeofsymbolism.com/images/ram-spirit-animal.jpg"
u = urlopen(URL)
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
photo = ImageTk.PhotoImage(im)
When running this code I get AttributeError: type object 'Image' has no attribute 'open'(line 18) as Traceback. It seems like tkinter and PIL are overlapping with the open function.
How can I avoid this?
Solved by importing the needed tkinter modules like this:
from tkinter.constants import *
and
from tkinter import Label

Tkinter:Cant place image which imported from Pixmap inside text widget using button

So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/

How to import and display list of images in GUI using Tkinter?

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.

Viewing external images in a list (Tkinter in python)

im trying to learn Python and doing some test apps.
Right now im creating a type of image viewer for viewing external images. But have some problems.
I've successfully worked out on how to view the image. But i need to view it as a function, so the image can be updated.
This is what i use for just viewing the image:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
imagelinks = []
***** Here is a crawler that provides image urls from a webpage into the above list ***
root = tk.Tk()
listvalue = 1
url = (imagelinks[listvalue])
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()
Everything works well, the image 1 from the list shows up properly.
The problem im having is that i want to add a prev and next button which increment the value of listvalue-=1 and +=1 but simply doing that wont work since it wont update the image in the tkinter window.
Also tried with the Tkinter's update() in my buttons function, but didn't help much either.
Anyone got some input on how to get it to work?
Update:
Tried to put it in a function like this. It is resizing the windows to the proper size, but wont show the image.
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
link='http://img.khelnama.com/sites/default/files/previewimage/features/2013/Aug/IMG- Reliance_logo(1).jpg'
def showimg(currentimg):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
showimg(link)
root.mainloop()
You will need to put your code that retrieves and displays the image in a definition, and pass the list item that it is meant to use as a parameter. That way on a button press, you can increment or decrement the index, and call your own update function you made.
Edit:
Try this then
label = tk.Label()
label.pack()
def showimg(currentimg, label):
url = currentimg
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label.config(image = image)
showimg(link, label)

How to display a png file from a webpage on a tk label in Python?

I'm new to python and I'm on a windows 7 64 bit with python 3.3. I can display a gif image with the following code. However I can't make it work with png files. How to do that? Thanks.
import urllib
import urllib.request
import tkinter as tk
root = tk.Tk()
url = "http://www.baidu.com/img/bdlogo.gif"
u = urllib.request.urlopen(url)
raw_data = u.read()
u.close()
import base64
b64_data = base64.encodestring(raw_data)
image = tk.PhotoImage(data=b64_data)
label = tk.Label(image=image)
label.pack()
You should use PIL (or pillow). You can find pillow windows binary here.
Try following example after you install pillow:
from io import BytesIO
import urllib
import urllib.request
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
with urllib.request.urlopen(url) as u:
raw_data = u.read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()

Categories

Resources