Esta GtkApplication muestra una archivo de imagen de la carpeta actual.
Si el archivo de imagen no se carga correctamente, la imagen tendrá un icono de «imagen rota». El archivo
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)
Otra manera de obtener lo que se tiene en el ejemplo es crear la imagen como una instancia de otra clase y añadírsela a la instancia de MyWindow
en el método do_activate(self)
:
# 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()
Para usar este fragmento de código necesitará aádir el código que importa Gtk
y GdkPixbuf
desde gi.repository
y las líneas que crean una instancia de la ventana MyApplication
.
Para cargar una imagen por red, use set_from_pixbuf(pixbuf)
, donde pixbuf
es un 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)
Si preserve_aspect_ratio=True
puede usar new_from_file_at_size(nombre_archivo, anchura, altura)
. Si anchura
o altura
son -1
, no se restringen.
Para cargar de un flujo de entrada, consulte new_from_stream()
y new_from_stream_at_scale()
en la documentación.
En este ejemplo se usa lo siguiente:
GtkImage
GtkWindow