Skip to content

Switch

Usage

A Switch's button has a text label, and two states: True (on, checked); and False (off, unchecked).

import toga

switch = toga.Switch()

# What is the current state of the switch?
print(f"The switch is {switch.value}")

Notes

  • The button and the label are considered a single widget for layout purposes.
  • The visual appearance of a Switch is not guaranteed. On some platforms, it will render as a checkbox. On others, it will render as a physical "switch" whose position (and color) indicates if the switch is active. When rendered as a checkbox, the label will appear to the right of the checkbox. When rendered as a switch, the label will be left-aligned, and the switch will be right-aligned.
  • You should avoid setting a height style property on Switch widgets. The rendered height of the Switch widget will be whatever the platform style guide considers appropriate; explicitly setting a height for the widget can lead to widgets that have a distorted appearance.
  • On macOS, the text color of the label cannot be set directly; any color style directive will be ignored.

Reference

Bases: Widget

Source code in core/src/toga/widgets/switch.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
class Switch(Widget):
    def __init__(
        self,
        text: str,
        id: str | None = None,
        style: StyleT | None = None,
        on_change: toga.widgets.switch.OnChangeHandler | None = None,
        value: bool = False,
        enabled: bool = True,
        **kwargs,
    ):
        """Create a new Switch widget.

        :param text: The text to display beside the switch.
        :param id: The ID for the widget.
        :param style: A style object. If no style is provided, a default style
            will be applied to the widget.
        :param value: The initial value for the switch.
        :param on_change: A handler that will be invoked when the switch changes
            value.
        :param enabled: Is the switch enabled (i.e., can it be pressed?).
            Optional; by default, switches are created in an enabled state.
        :param kwargs: Initial style properties.
        """
        super().__init__(id, style, **kwargs)

        self.text = text

        # Set a dummy handler before installing the actual on_change, because we do not
        # want on_change triggered by the initial value being set
        self.on_change = None
        self.value = value

        self.on_change = on_change

        self.enabled = enabled

    def _create(self) -> Any:
        return self.factory.Switch(interface=self)

    @property
    def text(self) -> str:
        """The text label for the Switch.

        `None`, and the Unicode codepoint U+200B (ZERO WIDTH SPACE), will be
        interpreted and returned as an empty string. Any other object will be
        converted to a string using `str()`.

        Only one line of text can be displayed. Any content after the first
        newline will be ignored.
        """
        return self._impl.get_text()

    @text.setter
    def text(self, value: object) -> None:
        if value is None or value == "\u200b":
            value = ""
        else:
            # Switch text can't include line breaks. Strip any content
            # after a line break (if provided)
            value = str(value).split("\n")[0]

        self._impl.set_text(value)
        self.refresh()

    @property
    def on_change(self) -> OnChangeHandler:
        """The handler to invoke when the value of the switch changes."""
        return self._on_change

    @on_change.setter
    def on_change(self, handler: toga.widgets.switch.OnChangeHandler) -> None:
        self._on_change = wrapped_handler(self, handler)

    @property
    def value(self) -> bool:
        """The current state of the switch, as a Boolean.

        Any non-Boolean value will be converted to a Boolean.
        """
        return self._impl.get_value()

    @value.setter
    def value(self, value: object) -> None:
        self._impl.set_value(bool(value))

    def toggle(self) -> None:
        """Reverse the current value of the switch."""
        self.value = not self.value

on_change property writable

The handler to invoke when the value of the switch changes.

text property writable

The text label for the Switch.

None, and the Unicode codepoint U+200B (ZERO WIDTH SPACE), will be interpreted and returned as an empty string. Any other object will be converted to a string using str().

Only one line of text can be displayed. Any content after the first newline will be ignored.

value property writable

The current state of the switch, as a Boolean.

Any non-Boolean value will be converted to a Boolean.

__init__(text, id=None, style=None, on_change=None, value=False, enabled=True, **kwargs)

Create a new Switch widget.

:param text: The text to display beside the switch. :param id: The ID for the widget. :param style: A style object. If no style is provided, a default style will be applied to the widget. :param value: The initial value for the switch. :param on_change: A handler that will be invoked when the switch changes value. :param enabled: Is the switch enabled (i.e., can it be pressed?). Optional; by default, switches are created in an enabled state. :param kwargs: Initial style properties.

Source code in core/src/toga/widgets/switch.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def __init__(
    self,
    text: str,
    id: str | None = None,
    style: StyleT | None = None,
    on_change: toga.widgets.switch.OnChangeHandler | None = None,
    value: bool = False,
    enabled: bool = True,
    **kwargs,
):
    """Create a new Switch widget.

    :param text: The text to display beside the switch.
    :param id: The ID for the widget.
    :param style: A style object. If no style is provided, a default style
        will be applied to the widget.
    :param value: The initial value for the switch.
    :param on_change: A handler that will be invoked when the switch changes
        value.
    :param enabled: Is the switch enabled (i.e., can it be pressed?).
        Optional; by default, switches are created in an enabled state.
    :param kwargs: Initial style properties.
    """
    super().__init__(id, style, **kwargs)

    self.text = text

    # Set a dummy handler before installing the actual on_change, because we do not
    # want on_change triggered by the initial value being set
    self.on_change = None
    self.value = value

    self.on_change = on_change

    self.enabled = enabled

toggle()

Reverse the current value of the switch.

Source code in core/src/toga/widgets/switch.py
106
107
108
def toggle(self) -> None:
    """Reverse the current value of the switch."""
    self.value = not self.value

Bases: Protocol

Source code in core/src/toga/widgets/switch.py
11
12
13
14
15
16
17
class OnChangeHandler(Protocol):
    def __call__(self, widget: Switch, **kwargs: Any) -> None:
        """A handler to invoke when the value is changed.

        :param widget: The Switch that was changed.
        :param kwargs: Ensures compatibility with arguments added in future versions.
        """

__call__(widget, **kwargs)

A handler to invoke when the value is changed.

:param widget: The Switch that was changed. :param kwargs: Ensures compatibility with arguments added in future versions.

Source code in core/src/toga/widgets/switch.py
12
13
14
15
16
17
def __call__(self, widget: Switch, **kwargs: Any) -> None:
    """A handler to invoke when the value is changed.

    :param widget: The Switch that was changed.
    :param kwargs: Ensures compatibility with arguments added in future versions.
    """