Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load and show an image from the web in Python with Gtk 3?

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.

like image 992
Daniel Jonsson Avatar asked Jul 18 '12 20:07

Daniel Jonsson


People also ask

How do I display an image in GTK?

Various kinds of object can be displayed as an image; most typically, you would load a GdkPixbuf (“pixel buffer”) from a file, and then display that. There's a convenience function to do this, gtk_image_new_from_file(), used as follows: GtkWidget *image; image = gtk_image_new_from_file ("myfile. png");

What is GTK in Python?

GTK is a multi-platform toolkit for creating graphical user interfaces. It is created in C language. GTK has been designed from the ground up to support a range of languages, including Python, Ruby, and Perl. The GTK library is also called the GIMP Toolkit.


2 Answers

This will work;

from gi.repository import Gtk
from gi.repository.GdkPixbuf import Pixbuf
from gi.repository import Gio
import urllib

url = 'http://lolcat.com/images/lolcats/1338.jpg'
response = urllib.request.urlopen(url)
input_stream = Gio.MemoryInputStream.new_from_data(response.read(), None)
pixbuf = Pixbuf.new_from_stream(input_stream, None)
image = Gtk.Image()
image.set_from_pixbuf(pixbuf)
like image 165
BreinBaas Avatar answered Sep 22 '22 20:09

BreinBaas


I haven't found any documentation on PixBuf. Therefore, I can't answer which arguments new_from_stream takes. For the record, the error message I was given was

TypeError: new_from_stream() takes exactly 2 arguments (1 given)

But I can give you a simple solution which might even improve your application. Saving the image to a temporary file includes caching.

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)
fname = url.split("/")[-1]
f = open(fname, "wb")
f.write(response.read())
f.close()
response.close()
image = Gtk.Image()
image.set_from_pixbuf(Pixbuf.new_from_file(fname))

I'm aware it's not the cleanest code (URL could be malformed, resource opening could fail, ...) but it should be obvious whats's the idea behind.

like image 28
f4lco Avatar answered Sep 22 '22 20:09

f4lco