Cette application Gtk affiche un fichier image issu du dossier en cours.
If the image file is not loaded successfully, the image will contain a
"broken image" icon.
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)
Une autre manière d'obtenir ce qu'il y a dans cet exemple est de créer l'image en tant qu'exemple d'une autre classe et de l'ajouter à MyWindow
dans la méthode 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()
To use this code snippet, you will need to add the code that imports
Gtk
and GdkPixbuf
from gi.repository
and lines that instantiate the MyApplication
window.
To load an image over a network use
set_from_pixbuf(pixbuf)
, where pixbuf
is a
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
est vrai, utilisez new_from_file_at_size(nomdufichier, largeur, hauteur)
. Si largeur
ou hauteur
est -1
, il n'y a pas de contrainte.
For loading from an input stream, see new_from_stream()
and new_from_stream_at_scale()
in the documentation.
Dans cet exemple, les éléments suivants sont utilisés :
GtkImage
GtkWindow