I don't use python 3, but I can give an answer that works in python 2.5+. I assume the code will work nearly identically on python 3.
Before we get started, we need to import Tkinter and create the root window:
import Tkinter as tk
root = tk.Tk()
Next, to download the image using urllib:
import urllib
URL = "http://www.smellymonkey.com/monkeys/images/ill-monkey.gif"
u = urllib.urlopen(URL)
raw_data = u.read()
u.close()
You now have the binary data for the image in the variable raw_data
. Tkinter accepts a data
option, but unfortunately you can't feed it this raw data. It expects the data to be encoded as base64. This is easy enough to do:
import base64
b64_data = base64.encodestring(raw_data)
image = tk.PhotoImage(data=b64_data)
Now that we have an image, time to put it on the screen:
label = tk.Label(image=image)
label.pack()
You should now see the image on the screen.
The above only works for .gif images, but other image formats are almost as easy to handle. The simplest method is to write the raw image data to disk (or use urllib to directly download the data to a file) and reference the file when creating the PhotoImage
object. Of course, this only works for image formats directly supported by the PhotoImage
class.
Your other choice is to use PIL (Python Image Library) which supports many different image formats. The technique remains roughly the same, only you must first create a PIL image, then convert it to a format usable by Tkinter. For more information about PIL consult the Python Imaging Library Handbook and also the effbot documentation on The Tkinter PhotoImage Class
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…