Short Example of GSettings Bindings with Python using a Gtk Switch

I made this short example of Gtk.Switch to modify a setting in Gnome with a single line of code that supports bindings and callbacks for the properties of the widget (Including value_changed). As stated at Gnome’s GSettings Site, “Gsettings let’s you bind object properties directly to settings” and “it uses the default Gio mapping functions to map between the settings and property values”.

Although this PyGI example is very short, I thought it was a good idea to post it since it could be useful to someone else since this Gsettings bindings are documented in C and not in Python yet.

The script creates a Gtk Switch with its label both packed into a Gtk Window. The property of Gtk.Switch is “active”, same as Gtk.CheckButton (boolean). The setting I use for this example lets you hide or show the Desktop Icons in Gnome (Not sure if the best one, but you can experiment with the one of your choice); schema “org.gnome.desktop.background”, key “show-desktop-icons”, and  in python you can set GSettingsBindFlags with Gio.SettingsBindFlags. Example:  G_SETTINGS_BIND_DEFAULT  is Gio.SettingsBindFlags.DEFAULT .

If you change the same setting from your terminal or Dconf-Editor while the script is running, you will notice how the switch will update the change by its own at the same time.

#! /usr/bin/python

from gi.repository import Gtk, Gio

class Example(Gtk.Window):

    def __init__(self):
        # Setup the window with title and border width.
        Gtk.Window.__init__(self, type=Gtk.WindowType.TOPLEVEL,
                                  title="Gsettings Switch Example",
                                  resizable=False,
                                  border_width=10)
        # Create and bind the Gtk Switch with the gsettings schema and its key.
        switch = Gtk.Switch()
        setting = Gio.Settings.new("org.gnome.desktop.background")
        setting.bind("show-desktop-icons", switch, "active", Gio.SettingsBindFlags.DEFAULT)

        # Create the label for the switch
        label = Gtk.Label("Show Icons on the Desktop")

        # Position the Switch and its Label inside a Horizontal child box.
        box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 40)
        box.pack_start(label, False, False, 10)
        box.pack_end(switch, False, False, 10)

        # Add the child box to the window
        self.add(box)
        self.connect("destroy", Gtk.main_quit)
        self.show_all()
        Gtk.main()

if __name__ == "__main__":
    Example()

Follow

Get every new post delivered to your Inbox.