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:
- You need to install PIL (it's not standard on Python 2.7).
- Yes, you need to import
Tkinter
in Python 2.7;tkinter
is for Python 3.x - You can use the code above (provided you install PIL).
Also,
- In Python 2.7 you need
urllib
and noturllib.request
- Seems you can't use
with....open(x) as fname
in 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?"