Skip to content

Switch

A simple switch widget which stores a boolean value.

  • Focusable
  • Container

Example

The example below shows switches in various states.

SwitchApp Example switches ▔▔▔▔▔▔▔▔ off:      ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ on:       ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ focused:  ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ custom:   ▁▁▁▁▁▁▁▁

from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Switch, Static


class SwitchApp(App):
    def compose(self) -> ComposeResult:
        yield Static("[b]Example switches\n", classes="label")
        yield Horizontal(
            Static("off:     ", classes="label"),
            Switch(animate=False),
            classes="container",
        )
        yield Horizontal(
            Static("on:      ", classes="label"),
            Switch(value=True),
            classes="container",
        )

        focused_switch = Switch()
        focused_switch.focus()
        yield Horizontal(
            Static("focused: ", classes="label"), focused_switch, classes="container"
        )

        yield Horizontal(
            Static("custom:  ", classes="label"),
            Switch(id="custom-design"),
            classes="container",
        )


app = SwitchApp(css_path="switch.css")
if __name__ == "__main__":
    app.run()
Screen {
    align: center middle;
}

.container {
    height: auto;
    width: auto;
}

Switch {
    height: auto;
    width: auto;
}

.label {
    height: 3;
    content-align: center middle;
    width: auto;
}

#custom-design {
    background: darkslategrey;
}

#custom-design > .switch--slider {
    color: dodgerblue;
    background: darkslateblue;
}

Reactive Attributes

Name Type Default Description
value bool False The value of the switch.

Bindings

The switch widget defines the following bindings:

Key(s) Description
enter,space Toggle the switch state.

Component Classes

The switch widget provides the following component classes:

Class Description
switch--slider Targets the slider of the switch.

Messages

Changed

Bases: Message

Posted when the status of the switch changes.

Can be handled using on_switch_changed in a subclass of Switch or in a parent widget in the DOM.

Attributes:

Name Type Description
value bool

The value that the switch was changed to.

input bool

The Switch widget that was changed.

control: Switch property

Alias for self.switch.

Additional Notes

  • To remove the spacing around a Switch, set border: none; and padding: 0;.

See Also