使用Gtk 3在Python中加载并显示图像? [英] Load and show an image from the web in Python with Gtk 3?
问题描述
我正在使用Python和GTK 3在Ubuntu 12.04上编写应用程序。我遇到的问题是我无法弄清楚如何在web应用程序中显示Gtk.Image以及来自web的图像文件。
这是就我来说:
from gi.repository import gtk
from gi.repository.GdkPixbuf import Pixbuf
import urllib2
$ b $ url url ='http://lolcat.com/images/lolcats/1338.jpg'
response = urllib2.urlopen(url)
image = Gtk.Image()
image.set_from_pixbuf(Pixbuf.new_from_stream(response))
我认为除最后一行之外的所有内容都是正确的。
我还没有找到关于PixBuf的任何文档。因此,我无法回答哪些参数 new_from_stream
需要。对于记录,我给出的错误消息是:
TypeError:new_from_stream()只需2个参数(给出1)
但我可以给你一个简单的解决方案,甚至可以改进你的应用程序。将图像保存到临时文件中包含缓存。
from gi.repository import gtk
from gi.repository.GdkPixbuf导入Pixbuf
导入urllib2
$ b $ 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))
我知道这不是最干净的代码(URL可能不正确,资源开放可能会失败,...),但它应该很明显是什么背后的想法。 / p>
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.
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.
这篇关于使用Gtk 3在Python中加载并显示图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!