# Color picker

> Pick a color, a gradient or a masked fill; swatches show them. A native Pyzed component for Python desktop GUIs, with a live preview, code examples and its API.

Source: https://albakore.github.io/pyzed/library/color-picker/

:::tip[In plain words]
A palette to choose a color, its transparency, or a blend of colors.
:::

`ui.ColorPicker` is a component that picks a color with alpha, a linear gradient (stops you add, drag and remove, plus an angle) or a fill with an opacity mask. `on_change` receives an event whose `value` is a `"#rrggbb[aa]"` string, a `pz.Gradient` or a `pz.Paint`, all valid backgrounds. `ui.color_swatch` shows any of them over a checkerboard.

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

**Code:**

```python
pz.row([
    ui.ColorPicker(value="#3b82f6cc", on_change=on_change),
    pz.column([
        ui.color_swatch("#3b82f6", size=28),
        ui.color_swatch("#a1c181aa", size=28),
        ui.color_swatch(pz.Gradient(["#f97316", "#7c3aed"], angle=90), size=28),
    ], spacing=8),
], spacing=16)
```

:::note[New]
This component was added recently. Tell us how it works for you in the [issue tracker](https://github.com/albakore/pyzed/issues).
:::

## When to use

- For theme editors, drawing apps and style properties.
- Show a `color_swatch` and open the picker in a [Popover](https://albakore.github.io/pyzed/library/popover/) when it is pressed.

## Usage

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

class Styles(pz.App):
    def __init__(self):
        self.fill = "#3b82f6"

    def view(self):
        return pz.row([
            ui.ColorPicker(value=self.fill, on_change=lambda e: setattr(self, "fill", e.value)),
            pz.container(width=120, height=120, bg=self.fill, radius=8),
        ], spacing=16)
```

## 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.
:::

### Options

```python
ui.ColorPicker(value="#3b82f6cc", on_change=on_change)
```

```python
ui.ColorPicker(value="#a1c181", alpha=False, gradients=False, masks=False,
               on_change=on_change)
```

```python
ui.ColorPicker(value="#e5c07b", gradients=False, masks=False,
               swatches=["#e06c75", "#e5c07b", "#98c379", "#61afef", "#c678dd"], on_change=on_change)
```

### Swatches

A swatch draws any color, gradient or paint over a checkerboard, so transparency shows.

```python
ui.color_swatch("#3b82f6", size=32)
```

```python
ui.color_swatch("#a1c181aa", size=32)
```

```python
ui.color_swatch(pz.Gradient(["#f97316", "#7c3aed"], angle=90), size=32)
```

```python
ui.checkerboard(96, 48, size=8)
```

## Events

Color picker has **2 events 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/).

It is a `pz.Component`, so it also raises `on_mount` and `on_unmount`, and its handlers get a `pz.Event` whose `value` holds the data.

| Event | Of | Handler gets | When |
| --- | --- | --- | --- |
| `on_change` | `ui.ColorPicker` | `(event)` | Receives `event.value`. |
| `on_press` | `ui.color_swatch` | `()` | Makes it clickable. |

**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 Styles(pz.App):
    def __init__(self):
        self.fill = "#3b82f6"

    def picked(self, event):             # a pz.Component: the color is event.value
        self.fill = event.value

    def view(self):
        return pz.row([
            ui.ColorPicker(value=self.fill, on_change=self.picked),
            pz.container(width=80, height=80, bg=self.fill, radius=8),
            ui.color_swatch("#ef4444", on_press=lambda: setattr(self, "fill", "#ef4444")),
        ], spacing=16)
```

**Declarative:**

```python
from dataclasses import dataclass

@dataclass
class Fill:
    color: str

class Styles(pz.App):
    fill = "#3b82f6"

    def update(self, message):
        match message:
            case Fill(color):
                self.fill = color

    def view(self):
        return pz.row([ui.ColorPicker(value=self.fill, on_change=lambda e: Fill(e.value)),
                       ui.color_swatch("#ef4444", on_press=Fill("#ef4444"))], spacing=16)
```

**Functional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    fill: str = "#3b82f6"

def view(state, set_state):
    return pz.row([ui.ColorPicker(value=state.fill, on_change=lambda e: set_state(fill=e.value)),
                   pz.container(width=80, height=80, bg=state.fill, radius=8)], spacing=16)
```

## Properties and API

### `ui.ColorPicker`

```python
class ColorPicker
```

A component that picks a color with alpha, a linear gradient (stops you add, drag and remove, plus an angle) or a fill with an opacity mask. `on_change` gets a `"#rrggbb[aa]"` string, a `pz.Gradient` or a `pz.Paint`, all valid as a `background`. Pass the picked value back as `value`. See [Styles](https://albakore.github.io/pyzed/theming/styles/#color-picker).

| Property | Default | Description |
| --- | --- | --- |
| `value` | `"#3b82f6"` | A color, theme token, `pz.Gradient` or `pz.Paint`. |
| `alpha` | `True` | Shows the alpha bar and field. |
| `gradients` | `True` | Shows the Solid/Gradient switch. |
| `masks` | `True` | Shows the mask editor. |
| `swatches` | `None` | Quick colors (default: the theme's accent and status colors). |

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

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

### `ui.color_swatch`

```python
color_swatch(value, *, size=20, on_press=None)
```

A small square showing a color, gradient or paint over a checkerboard.

| Property | Default | Description |
| --- | --- | --- |
| `value` | *required* | What to show. |
| `size` | `20` | Side in pixels. |

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

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

### `ui.checkerboard`

```python
checkerboard(width, height, size=6)
```

A light/dark checkerboard to draw under translucent colors.

| Property | Default | Description |
| --- | --- | --- |
| `width` | *required* | Width. |
| `height` | *required* | Height. |
| `size` | `6` | Cell size. |

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

## Related

- [Popover](https://albakore.github.io/pyzed/library/popover/): Floating content at a point: context menus, color pickers.
- [Card](https://albakore.github.io/pyzed/library/card/): A bordered surface with an optional title and actions.
