2012-07-18 87 views
4

我正在用Python和GTK 3在Ubuntu 12.04上编写一个应用程序。我遇到的问题是我无法弄清楚我应该如何在Web应用程序中用图像文件显示Gtk.Image。使用Gtk 3在Python中加载并显示图像?

这是据我已经来了:

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)) 

我觉得一切都只是最后一行正确。

回答

1

我还没有找到关于PixBuf的任何文档。因此,我无法回答new_from_stream采用哪个参数。为了记录在案,我得到的错误信息是

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

但我可以给你一个简单的解决方案,它甚至可能会提高你的应用程序。将图像保存到临时文件包括缓存。

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)) 

我知道这不是最干净的代码(网址就可能会畸形,资源开放可能会失败,...),但它应该是显而易见的是什么背后的想法。

5

这将工作;

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

url = 'http://lolcat.com/images/lolcats/1338.jpg' 
response = urllib2.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)