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

../../../_images/switch.png
 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        if switch.props.active:
30            state = 'on'
31        else:
32            state = 'off'
33        print('Switch was turned', state)
34
35
36def on_activate(app):
37    win = SwitcherWindow(application=app)
38    win.present()
39
40
41app = Gtk.Application(application_id='com.example.App')
42app.connect('activate', on_activate)
43
44app.run(None)