# Aviso

> Un aviso en línea con título, texto y acciones. Un componente nativo de Pyzed para GUIs de escritorio en Python, con vista previa, ejemplos y su API.

Source: https://albakore.github.io/pyzed/es/library/callout/

:::tip[En pocas palabras]
Una caja de color dentro de la página con un mensaje: un consejo, un aviso o un error.
:::

Un aviso en línea (un callout o banner): un icono, un título, una descripción opcional, botones de acción y un botón de cerrar con `on_dismiss`. `tint` es `"info"` (por defecto), `"success"`, `"warning"`, `"error"` o cualquier token del tema.

`ui.callout` · Categoría: [Estado y avisos](https://albakore.github.io/pyzed/es/library/#estado-y-avisos) · [Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#callout)

**Código:**

```python
pz.column([
    ui.callout("A new version is out", "Pyzed 0.4 adds the component designer.", tint="info",
               actions=[ui.button("What's new", on_open, size="sm")], on_dismiss=on_dismiss),
    ui.callout("Could not save", "The file is read-only.", tint="error"),
], spacing=10, width=520)
```

## Cuándo usarlo

- Para mensajes que pertenecen a un lugar de la interfaz: un archivo de solo lectura, una versión nueva, una sincronización fallida.
- Para mensajes pasajeros, usa una [Notificación](https://albakore.github.io/pyzed/es/library/toast/).

## Uso

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

pz.column([
    ui.callout("A new version is out", "Pyzed 0.4 adds the component designer.", tint="info",
               actions=[ui.button("What's new", on_open, size="sm")], on_dismiss=on_dismiss),
    ui.callout("Could not save", "The file is read-only.", tint="error"),
], spacing=10, width=520)
```

## Variantes

:::note[Sobre estas capturas]
Cada captura la graba pyzed mismo, fuera de pantalla a 2x, en One Dark o One Light según el tema de este sitio, y recortada al componente para que se vea a su tamaño real. El puntero pasa por encima, pulsa o escribe en él; un componente que no reacciona al puntero recorre algunos temas. Con movimiento reducido ves el primer fotograma. Abre **Código** bajo una captura para ver el fragmento que la dibuja; los nombres libres como `on_save` son tus propios callbacks.
:::

### Tinte

Cada tinte elige un icono acorde; `icon=` elige otro.

```python
pz.container(ui.callout("Heads up", "Pyzed 0.5 is out."), width=380)
```

```python
pz.container(ui.callout("Synced", "All changes are saved.", tint="success"), width=380)
```

```python
pz.container(ui.callout("Unsaved changes", "Save before closing.", tint="warning"), width=380)
```

```python
pz.container(ui.callout("Could not save", "The file is read-only.", tint="error"), width=380)
```

```python
pz.container(ui.callout("Tip", "Ctrl+Shift+P opens the palette.", tint="accent", icon="lightbulb"), width=380)
```

### Contenido

```python
pz.container(ui.callout("Read-only file"), width=380)
```

```python
pz.container(ui.callout("A new version is out", "Restart to update.",
                        actions=[ui.button("Restart", on_restart, size="sm")]), width=380)
```

```python
pz.container(ui.callout("Welcome!", "Open a folder to start.", on_dismiss=on_dismiss), width=380)
```

## Eventos

Aviso tiene **1 evento propios**, en la tabla de abajo. Como todo widget, también tiene los **18 eventos comunes** (`click`, `double_click`, `right_click`, `mouse_enter`, `drag`, `key_down`, `resize`…), que se conectan con `.on(...)`: mira [Eventos](https://albakore.github.io/pyzed/es/guides/events/) y [Eventos de cada componente](https://albakore.github.io/pyzed/es/library/events/).

| Evento | El handler recibe | Cuándo |
| --- | --- | --- |
| `on_dismiss` | `()` | Añade un botón de cerrar. |

**El handler recibe** es lo que Pyzed le pasa a tu función: `()` es nada. Cualquier handler también puede ser un mensaje (un valor que no se puede llamar), que va a `update()`.

### Manejar los eventos

Los mismos eventos escritos de tres formas. **Imperativa**: métodos de la app que cambian `self`. **Declarativa**: los handlers producen mensajes y un único `update()` decide. **Funcional**: una función pura dibuja un estado inmutable y pide cambios con `set_state(...)`. Mira [Imperativo, declarativo y funcional](https://albakore.github.io/pyzed/es/guides/code-styles/).

**Imperativo:**

```python
class Updates(pz.App):
    def __init__(self):
        self.visible = True

    def view(self):
        if not self.visible:
            return ui.muted("No news.")
        return ui.callout("A new version is out", "Pyzed adds the component designer.", tint="info",
                          on_dismiss=lambda: setattr(self, "visible", False))   # adds the ✕
```

**Declarativo:**

```python
class Updates(pz.App):
    visible = True

    def update(self, message):
        if message == "dismiss":
            self.visible = False

    def view(self):
        return ui.callout("A new version is out", tint="info", on_dismiss="dismiss") if self.visible \
            else ui.muted("No news.")
```

**Funcional:**

```python
from dataclasses import dataclass

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

def view(state, set_state):
    if not state.visible:
        return ui.muted("No news.")
    return ui.callout("A new version is out", tint="info", on_dismiss=lambda: set_state(visible=False))
```

## Propiedades y API

### `ui.callout`

```python
callout(
    title,
    description=None,
    *,
    tint='info',
    icon=None,
    actions=(),
    on_dismiss=None,
    theme=None,
)
```

Un aviso en línea (un callout o banner).

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `title` | *obligatorio* | Título (texto o widget). |
| `description` | `None` | Texto secundario. |
| `tint` | `"info"` | `"info"`, `"success"`, `"warning"`, `"error"` o `"hint"`: elige el color y el icono. |
| `icon` | `None` | Nombre de un icono de Lucide (`pyzed icons` los lista). |
| `actions` | `()` | Widgets extra (normalmente botones) que se muestran como acciones. |
| `theme` | `None` | Tema a usar en lugar del actual (`pyzed.theme.current()`). |

Eventos: `on_dismiss` ([eventos](#eventos)).

[Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#callout)

## Relacionados

- [Notificación](https://albakore.github.io/pyzed/es/library/toast/): Notificaciones apiladas en la esquina inferior derecha.
- [Alerta](https://albakore.github.io/pyzed/es/library/alert/): Un mensaje con un botón.
- [Estado vacío](https://albakore.github.io/pyzed/es/library/empty-state/): Un marcador centrado para listas y búsquedas vacías.
