이 GtkApplication에서는 현재 디렉터리의 그림파일을 보여줍니다.
그림 파일을 제대로 불러오지 않았다면, 그림에 "깨진 그림" 아이콘이 들어갑니다. 이 코드가 동작하려면 현재 디렉터리에
from gi.repository import Gtk
import sys
class MyWindow(Gtk.ApplicationWindow):
# create a window
def __init__(self, app):
Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)
self.set_default_size(300, 300)
# create an image
image = Gtk.Image()
# set the content of the image as the file filename.png
image.set_from_file("gnome-image.png")
# add the image to the window
self.add(image)
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
win.show_all()
def do_startup(self):
Gtk.Application.do_startup(self)
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
우리 예제에서 그림을 다른 클래스의 인스턴스로 만들고 do_activate(self)
메서드에서 MyWindow
의 인스턴스로 초기화 하는 다른 방법이 있습니다:
# a class to create a window
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)
self.set_default_size(300, 300)
# a class to create an image
class MyImage(Gtk.Image):
def __init__(self):
Gtk.Image.__init__(self)
self.set_from_file("gnome-image.png")
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
# create an instance of MyWindow
win = MyWindow(self)
# create an instance of MyImage and add it to the window
win.add(MyImage())
# show the window and everything on it
win.show_all()
이 코드 부분을 사용하려면, gi.repository
에서 Gtk
와 GdkPixbuf
를 임포팅하는 코드와 MyApplication
창을 초기화하는 여러 줄의 코드를 추가해야 합니다.
네트워크에서 그림을 불러오려면 set_from_pixbuf(pixbuf)
함수를 사용하십시오. 여기서 pixbuf
는 GdkPixbuf입니다.
from gi.repository import Gtk
from gi.repository import GdkPixbuf
import sys
class MyWindow(Gtk.ApplicationWindow):
# create a window
def __init__(self, app):
Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)
self.set_default_size(300, 300)
# create a pixbuf from file filename="gnome-image.png", with width=32
# and height=64 amd boolean preserve_aspect_ratio=False.
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale("gnome-image.png", 64, 128, False)
# create an image
image = Gtk.Image()
# set the content of the image as the pixbuf
image.set_from_pixbuf(pixbuf)
# add the image to the window
self.add(image)
preserve_aspect_ratio=True
이면, new_from_file_at_size(filename, width, height)
함수를 사용할 수 있습니다. width
또는 height
값이 -1
이면 제약을 받지 않습니다.
입력 스트림에서 불러오는 방법을 알아보려면, 문서에서 new_from_stream()
함수와 new_from_stream_at_scale()
함수 내용을 참고하십시오.
이 예제는 다음 참고자료가 필요합니다:
GtkImage
GtkWindow