python - how can I display a image from web?
I'm using Python to make a "web album viewer", but I meet some problem.
I use Tkinter to write GUI, urllib2 to fetch the image from web, PIL to handle the image
So the code is like this:
root = Tk()
frame = Frame(root)
frame.pack()
response = urllib2.urlopen(a_pic_url)
photo = ImageTk.PhotoImage(Image.open(response.read()))
label = Label(frame, image = photo)
label.pack()
it fails, and throws the following error message:
TypeError: file开发者_运维技巧() argument 1 must be (encoded string without NULL bytes), not str
How can I overcome this?
Thanks, and I'm sorry for my poor English.
Image.open
takes a filename or a file object, not a str
which is what is returned by read
.
Either save the image to a file then open that, or use Image.open(response)
, to use it directly on the file-like objected returned by urlopen
.
Edit: This should work if you're having trouble with the urlopen
object:
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO #works on on old versions of Python
response = urllib2.urlopen(a_pic_url)
photo = ImageTk.PhotoImage(file=BytesIO(response.read()))
There's nothing wrong with your English. There's a slight error in your code. It should be:
photo = ImageTk.PhotoImage(Image.open(response))
The .read()
part was messing with you.
That's because when using Image.open()
PIL waits for a filename, and what you gave is the content of the image file. Try to save the image before :
root = Tk()
frame = Frame(root)
frame.pack()
response = urllib2.urlopen(a_pic_url)
open(image_file_name, "wb+").write(response.read())
photo = ImageTk.PhotoImage(file=image_file_name)
label = Label(frame, image = photo)
label.pack()
精彩评论