Switch¶
A simple switch widget which stores a boolean value.
- Focusable
- Container
Example¶
The example below shows switches in various states.
from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Static, Switch
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.tcss")
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. |
Messages¶
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. |
Additional Notes¶
- To remove the spacing around a
Switch
, setborder: none;
andpadding: 0;
.
Bases: Widget
A switch widget that represents a boolean value.
Can be toggled by clicking on it or through its bindings.
The switch widget also contains component classes that enable more customization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
The initial value of the switch. |
False
|
|
bool
|
True if the switch should animate when toggled. |
True
|
|
str | None
|
The name of the switch. |
None
|
|
str | None
|
The ID of the switch in the DOM. |
None
|
|
str | None
|
The CSS classes of the switch. |
None
|
|
bool
|
Whether the switch is disabled or not. |
False
|
|
RenderableType | None
|
Optional tooltip. |
None
|
BINDINGS
class-attribute
¶
BINDINGS = [
Binding(
"enter,space", "toggle_switch", "Toggle", show=False
)
]
Key(s) | Description |
---|---|
enter,space | Toggle the switch state. |
COMPONENT_CLASSES
class-attribute
¶
Class | Description |
---|---|
switch--slider |
Targets the slider of the switch. |
value
class-attribute
instance-attribute
¶
The value of the switch; True
for on and False
for off.
Changed
¶
toggle
¶
Toggle the switch value.
As a result of the value changing, a Switch.Changed
message will
be posted.
Returns:
Type | Description |
---|---|
Self
|
The |