# Switch

> An on/off switch for settings that apply at once. A native Pyzed component for Python desktop GUIs, with a live preview, code examples and its API.

Source: https://albakore.github.io/pyzed/library/switch/

:::tip[In plain words]
An on/off switch, like a light switch, for settings that change right away.
:::

An on/off toggle in the theme's accent color. `on_toggle` receives the new `bool`.

`ui.switch` · Category: [Forms](https://albakore.github.io/pyzed/library/#forms) · [Full reference →](https://albakore.github.io/pyzed/reference/ui/#switch)

**Code:**

```python
pz.column([
    ui.switch(True, on_toggle, label="Autosave"),
    ui.switch(False, on_toggle, label="Vim mode"),
], spacing=12)
```

## When to use

- For settings that take effect immediately (Wi-Fi, autosave, dark mode).
- Put it on the right of a [Field](https://albakore.github.io/pyzed/library/field/) to build settings screens.

## Usage

```python
import pyzed as pz
from pyzed import ui

class Settings(pz.App):
    def __init__(self):
        self.autosave = True

    def view(self):
        return ui.switch(self.autosave, lambda on: setattr(self, "autosave", on), label="Autosave")
```

## Variants

:::note[About these captures]
Each capture is recorded by pyzed itself, off-screen at 2x, in One Dark or One Light to match this site's theme, and cropped to the component so it shows at its real size. The pointer hovers, presses or types into it; a component that does not react to the pointer cycles through a few themes. With reduced motion you see the first frame. Open **Code** under a capture to see the snippet that draws it; free names such as `on_save` stand for your own callbacks.
:::

### State

```python
ui.switch(True, on_toggle, label="Autosave")
```

```python
ui.switch(False, on_toggle, label="Autosave")
```

```python
ui.switch(True, label="Sync (managed)")
```

```python
ui.switch(True, on_toggle)
```

### States and events

```python
ui.switch(True, on_toggle, label="Locked", disabled=True)
```

```python
ui.switch(True, on_toggle, label="Small", size="sm")
```

```python
ui.switch(True, on_toggle, label="Large", size="lg")
```

### Base widget

The `pz.*` widget underneath: no theme, every color and size is yours.

```python
pz.toggler(True, "pz.toggler", on_toggle=on_toggle, accent="#a1c181", size=22)
```

## Events

Switch has **1 event of its own**, listed below. Like every widget it also has the **18 common events** (`click`, `double_click`, `right_click`, `mouse_enter`, `drag`, `key_down`, `resize`…), attached with `.on(...)`: see [Events](https://albakore.github.io/pyzed/guides/events/) and [Events of every component](https://albakore.github.io/pyzed/library/events/).

| Event | Of | Handler gets | When |
| --- | --- | --- | --- |
| `on_toggle` | `ui.switch`, `pz.toggler` | `(checked)` | Callable that receives the new `bool` (or a message to send). |

**Handler gets** is what Pyzed passes to your callable: `()` means nothing. Any handler can also be a message (a value that is not callable), which goes to `update()`.

### Handling the events

The same events written three ways. **Imperative**: methods of the app change `self`. **Declarative**: the handlers produce messages and one `update()` decides. **Functional**: a pure function draws an immutable state and asks for changes with `set_state(...)`. See [Imperative, declarative and functional](https://albakore.github.io/pyzed/guides/code-styles/).

**Imperative:**

```python
class Settings(pz.App):
    def __init__(self):
        self.autosave = True

    def set_autosave(self, on):          # on_toggle: the new state
        self.autosave = on

    def view(self):
        return pz.column([
            ui.switch(self.autosave, self.set_autosave, label="Autosave"),
            ui.label("Saving as you type" if self.autosave else "Save with Ctrl+S"),
        ], spacing=8)
```

**Declarative:**

```python
from dataclasses import dataclass

@dataclass
class SetAutosave:
    on: bool

class Settings(pz.App):
    autosave = True

    def update(self, message):
        match message:
            case SetAutosave(on):
                self.autosave = on

    def view(self):
        return ui.switch(self.autosave, SetAutosave, label="Autosave")
```

**Functional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    autosave: bool = True

def view(state, set_state):
    return ui.switch(state.autosave, lambda on: set_state(autosave=on), label="Autosave")
```

## Tips

:::tip
Once clicked or reached with Tab it has the keyboard focus (a ring shows when you use the keys): Space or Enter flips it.
:::

## Properties and API

### `ui.switch`

```python
switch(
    checked,
    on_toggle=None,
    *,
    label=None,
    size='md',
    disabled=False,
    id=None,
    theme=None,
)
```

An on/off switch.

| Property | Default | Description |
| --- | --- | --- |
| `checked` | *required* | Current state. |
| `label` | `None` | Label text. |
| `size` | `"md"` | `"sm"`, `"md"` or `"lg"`. |
| `disabled` | `False` | Greys it out and ignores clicks. |
| `id` | `None` | Stable identifier used to focus or scroll it with a `Command`. |
| `theme` | `None` | Theme to use instead of the current one (`pyzed.theme.current()`). |

Events: `on_toggle` ([events](#events)).

[Full reference →](https://albakore.github.io/pyzed/reference/ui/#switch)

### `pz.toggler`

```python
toggler(
    checked,
    label=None,
    *,
    on_toggle=None,
    size=None,
    text_size=None,
    accent=None,
    bg=None,
    border_color=None,
    knob_color=None,
    color=None,
)
```

An on/off switch.

| Property | Default | Description |
| --- | --- | --- |
| `checked` | *required* | Current state. |
| `label` | `None` | Label text. |
| `size` | `None` | Switch height. |
| `text_size` | `None` | Text size. |
| `accent` | `None` | Accent color (active part). |
| `bg` | `None` | Background color (`"#rrggbb[aa]"`, `(r, g, b[, a])` or `"transparent"`). |
| `border_color` | `None` | Border color. |
| `knob_color` | `None` | Knob color. |
| `color` | `None` | Text or icon color. |

Events: `on_toggle` ([events](#events)).

[Full reference →](https://albakore.github.io/pyzed/reference/widgets/#toggler)

## Related

- [Checkbox](https://albakore.github.io/pyzed/library/checkbox/): A checkbox with an optional label.
- [Field](https://albakore.github.io/pyzed/library/field/): A settings row: title and description left, control right.
- [Settings group](https://albakore.github.io/pyzed/library/settings-group/): A titled block of field rows, for settings screens.
