Switch — PyGObject

Skip to main content
`Ctrl`+`K`

# Switch

A `Gtk.Switch` is a widget that has two states: on or off. The user can control which state should be active by clicking the empty area, or by dragging the handle.

You shouldn’t use the `activate` signal on the Gtk.Switch which is an action signal and emitting it causes the switch to animate. Applications should never connect to this signal, but use the `notify::active` signal, see the example here below.

## Example

     1import gi
     2
     3gi.require_version("Gtk", "4.0")
     4from gi.repository import Gtk
     5
     6
     7class SwitcherWindow(Gtk.ApplicationWindow):
     8    def __init__(self, **kargs):
     9        super().__init__(**kargs, title="Switch Demo")
    10
    11        hbox = Gtk.Box(spacing=6, homogeneous=True)
    12        hbox.props.margin_top = 24
    13        hbox.props.margin_bottom = 24
    14        self.set_child(hbox)
    15
    16        switch = Gtk.Switch()
    17        switch.connect("notify::active", self.on_switch_activated)
    18        switch.props.active = False
    19        switch.props.halign = Gtk.Align.CENTER
    20        hbox.append(switch)
    21
    22        switch = Gtk.Switch()
    23        switch.connect("notify::active", self.on_switch_activated)
    24        switch.props.active = True
    25        switch.props.halign = Gtk.Align.CENTER
    26        hbox.append(switch)
    27
    28    def on_switch_activated(self, switch, _gparam):
    29        state = "on" if switch.props.active else "off"
    30        print("Switch was turned", state)
    31
    32
    33def on_activate(app):
    34    win = SwitcherWindow(application=app)
    35    win.present()
    36
    37
    38app = Gtk.Application(application_id="com.example.App")
    39app.connect("activate", on_activate)
    40
    41app.run(None)