Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm writing an app on Ubuntu 12.04 with Python and GTK 3. The problem I have is that I can't figure out how I should do to show a Gtk.Image in my app with an image file from the web.

This is as far as I have come:

from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf
import urllib2

url = 'http://lolcat.com/images/lolcats/1338.jpg'
response = urllib2.urlopen(url)
image = Gtk.Image()
image.set_from_pixbuf(Pixbuf.new_from_stream(response))

I think everything is correct except the last line.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

According to the docs, new_from_stream() needs a Gio.InputStream and Gio.Cancellable as arguments.

You could also save the image on disk and remove when needed. Here is a very basic example:

import os
import urllib2
from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf


def quit_event(widget, event):
    os.remove(imgname)
    Gtk.main_quit()

imgname = '1338.jpg'
url = 'http://lolcat.com/images/lolcats/'+imgname
response = urllib2.urlopen(url)
with open(imgname, 'wb') as img:
    img.write(response.read())

image = Gtk.Image()
pb = Pixbuf.new_from_file(imgname)
image.set_from_pixbuf(pb)

window = Gtk.Window()
window.connect('delete-event', quit_event)
window.add(image)
window.show_all()
Gtk.main()

You should write to a better location though, maybe /tmp or a user-specified dir.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.