2012-07-18 8 views
4

저는 파이썬과 GTK 3을 사용하여 우분투 12.04에 응용 프로그램을 작성하고 있습니다. 문제는 웹에서 이미지 파일로 내 응용 프로그램에 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)

이었다 그러나 나는 당신에게, 심지어 응용 프로그램을 향상시킬 수있는 간단한 솔루션을 제공 할 수 있습니다. 임시 파일에이 L 지 저장에는 캐싱이 포함됩니다.

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

나는 그것이 깨끗한 코드가 아니라 알고 있어요 (URL이 기형화 될 수 자원 개방, ... 실패 할 수 있습니다)하지만 뒤에 아이디어 뭐죠 그것은 명백해야한다.

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)