Short Example of GSettings Bindings with Python using a Gtk SwitchPosted: April 3, 2012
I made this short example of a Gtk.Switch working in assembly with a setting writing a single line of code instead of several lines to bind the properties of the widget creating callbacks (value_changed binding is also included). As Gnome states, “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 it’s a very short and basic PyGI example, I thought it was a good idea to post it since it might be useful to someone else being this Gsettings feature documented in C and not in Python yet.
The script creates a Gtk Switch and its label both packed into the Window. The property of Gtk.Switch is “active”, same as Gtk.CheckButton (boolean). The setting I picked up for this example is the one that lets the file manager show the icons on the desktop (Not sure if the best one, but you can experiment with the one you prefer); 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 see how the change will be set in the switch as well.
#! /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()