Show internet image with Tkinter

vegaseat 4 Tallied Votes 2K Views Share

The code sample shows how to get an image from the internet and show it in a Tkinter label widget.

JeffGrigg commented: And your question is...? -1
''' Tk_PIL_Image_url.py
get a .jpg image from the internet and show it with
PIL and Tkinter

used PIL fork Pillow from:
https://pypi.python.org/pypi/Pillow/2.2.1#downloads
Windows installer:
Pillow-2.2.1.win32-py2.7.exe or
Pillow-2.2.1.win32-py3.3.exe

tested with Python27 and Python33  by  vegaseat  14nov2013
'''

from PIL import Image
from PIL import ImageTk
import io
try:
    # Python2
    from urllib2 import urlopen
    import Tkinter as tk
except ImportError:
    # Python3
    from urllib.request import urlopen
    import tkinter as tk

# get a URL based image from the internet
# if the url was very long, split it in half
part1 = "http://uploads.neatorama.com/wp-content/"
part2 = "uploads/2011/05/cogtrain-500x688.jpg"
url = part1 + part2
fin = urlopen(url)
# read into a memory stream
s = io.BytesIO(fin.read())
pil_image = Image.open(s)
# let PIL determine the size info
print(pil_image.size)

# create Tkinter window
root = tk.Tk()

# convert PIL image to something Tkinter can handle
tk_image = ImageTk.PhotoImage(pil_image)

# show the image in a label
label = tk.Label(root, image=tk_image)
label.pack()

root.mainloop()
Assembly Guy 72 Posting Whiz

@JeffGrigg the downvoter, this is a code snippet, not a thread. You might like to look a little more carefully before asking what the OP's question is :)

Nils_1 0 Newbie Poster

Nice practical example, works out of the box, upvote!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.