Application Resources

Resources that are closely tied to the functioning of an application, such as user interface (UI) files, are typically compiled together into a resource bundle that the application can load from a single location at run-time. The individual resources can then be referred to using resource paths which can also be passed to classes such as GtkImage, making them convenient to use.

The sections below provide a simple overview of resources and give information for developers using Python. For a more comprehensive description, see the GNOME API documentation for GResource.

Resource Bundles

The files to be compiled together into a resource bundle are listed in a resource description XML file that will look like the following:

<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/com/example/application">
    <file>ui/menus.ui</file>
    <file>ui/window.ui</file>
    <file>ui/style.css</file>
  </gresource>
</gresources>

Generally, if you are using a build system like Meson, resource bundles will be compiled for you when you build your application.

When compiled using the glib-compile-resources tool the files listed in the resource description file will be compiled to a bundle with a file name based on the original XML file – for example, the example.gresource.xml file will be compiled to the example.gresource file. The files to be included are located in the current working directory, not the directory containing the XML file.

Resource Paths

Each file listed in the resource description XML file will be stored with its path prefixed by the prefix given in the gresource element. So, in the above example, the file found at ui/menus.ui will need to be accessed at run-time using the /com/example/application/ui/menus.ui resource path.

Once a resource bundle has been loaded by calling Gio.Resource.load and obtaining a Resource object, it is typically registered by calling the object’s register method. This allows the resources stored within to be accessed using the GResource API. The application can then access its resources directly, but often paths to resources are passed to methods in other parts of the Gio and Gtk APIs.

For example, the Gtk.Builder class will accept resource paths and use them to access resources registered with the application:

builder = Gtk.Builder()
builder.add_from_resource('/com/example/application/ui/menus.ui')
builder.add_from_resource('/com/example/application/ui/window.ui')

This is more convenient than accessing files in the file system and should always work if the resource has been loaded and registered, and if the files contain the appropriate data for the APIs they are being supplied to – for example, only UI files should be passed to Gtk.Builder.