Skip to content Skip to sidebar Skip to footer

How To Add A Url Image To Tkinter In Python 2.7 Using Only The Standard Python Library?

I have seen many examples of how to show images in Tkinter using an image URL but none of those examples are working for me i.e. import urllib from Tkinter import * import io from

Solution 1:

This works, using python 2.7 on windows:

from io import BytesIO
import Tkinter as tk
import urllib  # not urllib.requestfrom PIL import Image, ImageTk

root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"

u = urllib.urlopen(url)
raw_data = u.read()
u.close()

im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
label = tk.Label(image=image)
label.pack()
root.mainloop()

To answer your questions:

  1. You need to install PIL (it's not standard on Python 2.7).
  2. Yes, you need to import Tkinter in Python 2.7; tkinter is for Python 3.x
  3. You can use the code above (provided you install PIL).

Also,

  1. In Python 2.7 you need urllib and not urllib.request
  2. Seems you can't use with....open(x) as fnamein urllib so you need to open and close the file explicitly.

Post a Comment for "How To Add A Url Image To Tkinter In Python 2.7 Using Only The Standard Python Library?"