# Checkbox

> A checkbox with an optional label. A native Pyzed component for Python desktop GUIs, with a live preview, code examples and its API.

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

:::tip[In plain words]
A square you tick to say yes to an option.
:::

A themed checkbox. `on_toggle` receives the new `bool`; `label` adds clickable text next to it.

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

**Code:**

```python
pz.column([
    ui.checkbox(True, on_toggle, label="Format on save"),
    ui.checkbox(False, on_toggle, label="Show hidden files"),
    ui.checkbox(True, on_toggle, label="Use tabs"),
], spacing=10)
```

## When to use

- For options that are applied later (a form you submit) or a list of independent choices.
- For a setting that takes effect at once, a [Switch](https://albakore.github.io/pyzed/library/switch/) reads better.

## Usage

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

class Settings(pz.App):
    def __init__(self):
        self.accepted = False

    def view(self):
        return ui.checkbox(self.accepted, lambda value: setattr(self, "accepted", value),
                           label="I accept the terms")
```

## 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.checkbox(True, on_toggle, label="Format on save")
```

```python
ui.checkbox(False, on_toggle, label="Format on save")
```

```python
ui.checkbox(True, label="Managed by your admin")
```

### Content

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

```python
pz.column([ui.checkbox(True, on_toggle, label="Python"),
           ui.checkbox(False, on_toggle, label="Rust"),
           ui.checkbox(True, on_toggle, label="TypeScript")], spacing=8)
```

### States and events

```python
ui.checkbox(None, on_toggle, label="Some files")
```

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

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

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

### Base widget

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

```python
pz.checkbox(True, "pz.checkbox", on_toggle=on_toggle, accent="#c678dd", size=18)
```

## Events

Checkbox 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.checkbox`, `pz.checkbox` | `(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.options = {"Format on save": True, "Show hidden files": False}

    def toggle(self, name, checked):     # on_toggle gets True or False
        self.options[name] = checked

    def view(self):
        return pz.column([
            ui.checkbox(on, lambda checked, name=name: self.toggle(name, checked), label=name)
            for name, on in self.options.items()
        ], spacing=10)
```

**Declarative:**

```python
from dataclasses import dataclass

@dataclass
class Toggle:
    name: str
    checked: bool

class Settings(pz.App):
    options = {"Format on save": True, "Show hidden files": False}

    def update(self, message):
        match message:
            case Toggle(name, checked):
                self.options = {**self.options, name: checked}

    def view(self):
        return pz.column([ui.checkbox(on, lambda c, n=name: Toggle(n, c), label=name)
                          for name, on in self.options.items()], spacing=10)
```

**Functional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    format_on_save: bool = True
    hidden_files: bool = False

def view(state, set_state):
    return pz.column([
        ui.checkbox(state.format_on_save, lambda c: set_state(format_on_save=c), label="Format on save"),
        ui.checkbox(state.hidden_files, lambda c: set_state(hidden_files=c), label="Show hidden files"),
    ], spacing=10)
```

## Tips

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

## Properties and API

### `ui.checkbox`

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

A checkbox. `checked=None` shows the mixed state (part of a group checked); clicking it checks it.

| 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/#checkbox)

### `pz.checkbox`

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

A checkbox.

| Property | Default | Description |
| --- | --- | --- |
| `checked` | *required* | Current state. |
| `label` | `None` | Label text. |
| `size` | `None` | Box size. |
| `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. |
| `check_color` | `None` | Check mark color. |
| `color` | `None` | Text or icon color. |

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

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

## Related

- [Switch](https://albakore.github.io/pyzed/library/switch/): An on/off switch for settings that apply at once.
- [Radio group](https://albakore.github.io/pyzed/library/radio-group/): Mutually exclusive options as radio buttons.
- [Field](https://albakore.github.io/pyzed/library/field/): A settings row: title and description left, control right.
