# Alerta

> Un mensaje con un botón. 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/alert/

:::tip[En pocas palabras]
Una caja de mensaje con un solo botón de Aceptar.
:::

Un mensaje con un solo botón de Aceptar. `kind` (`"info"`, `"success"`, `"warning"`, `"error"`) añade un icono.

`ui.alert` · Categoría: [Diálogos](https://albakore.github.io/pyzed/es/library/#diálogos) · [Referencia completa →](https://albakore.github.io/pyzed/es/reference/ui/#alert)

**Código:**

```python
ui.dialog_layer(main_view(), ui.alert("The export finished: 128 files were written.", on_close,
                                      title="Export", kind="success", width=360))
```

:::note[Nuevo]
Este componente se añadió hace poco. Cuéntanos qué tal te funciona en el [gestor de incidencias](https://github.com/albakore/pyzed/issues).
:::

## Cuándo usarlo

- Para avisar de algo que hay que confirmar (una exportación terminó, un archivo no se pudo abrir).

## Uso

```python
from pyzed import ui

ui.dialog_layer(main_view(), ui.alert("The export finished: 128 files were written.", on_close,
                                      title="Export", kind="success", width=360))
```

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

### Tipo

```python
ui.alert("The file was moved to the trash.", on_close, width=320)
```

```python
ui.alert("A new version is available.", on_close, kind="info", width=320)
```

```python
ui.alert("128 files were exported.", on_close, kind="success", title="Export", width=320)
```

```python
ui.alert("The disk is almost full.", on_close, kind="warning", width=320)
```

```python
ui.alert("notes.py could not be opened.", on_close, kind="error", title="Error", width=320)
```

### Opciones

```python
ui.alert("Shortcuts changed in this version.", on_close, ok_label="Got it", width=320)
```

## Eventos

Alerta 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_close` | `()` | El botón y el icono 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 Export(pz.App):
    def __init__(self):
        self.done = True

    def view(self):
        alert = ui.alert("128 files were written.", lambda: setattr(self, "done", False),   # on_close
                         title="Export", kind="success")
        return ui.dialog_layer(main_view(), alert if self.done else None)
```

**Declarativo:**

```python
class Export(pz.App):
    done = True

    def update(self, message):
        if message == "ok":
            self.done = False

    def view(self):
        return ui.dialog_layer(main_view(), ui.alert("128 files were written.", "ok", title="Export")
                               if self.done else None)
```

**Funcional:**

```python
from dataclasses import dataclass

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

def view(state, set_state):
    alert = ui.alert("128 files were written.", lambda: set_state(done=False), title="Export")
    return ui.dialog_layer(main_view(), alert if state.done else None)
```

## Propiedades y API

### `ui.alert`

```python
alert(message, on_close, *, title=None, kind=None, ok_label=None, width=400, theme=None)
```

Un mensaje con un botón.

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `message` | *obligatorio* | Texto o widget. |
| `title` | `None` | Título. |
| `kind` | `None` | `"info"`, `"success"`, `"warning"` o `"error"` añade un icono. |
| `ok_label` | `None` | Texto del botón (por defecto: Aceptar, traducido). |
| `width` | `400` | Ancho: píxeles, `"fill"`, `"shrink"` o `"fill:N"` (proporción). |
| `theme` | `None` | Tema a usar en lugar del actual (`pyzed.theme.current()`). |

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

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

## Relacionados

- [Confirmación](https://albakore.github.io/pyzed/es/library/confirm/): Una pregunta de sí o no, en rojo para acciones destructivas.
- [Capa de diálogo](https://albakore.github.io/pyzed/es/library/dialog-layer/): Centra un diálogo encima de tu vista con el fondo oscurecido.
- [Notificación](https://albakore.github.io/pyzed/es/library/toast/): Notificaciones apiladas en la esquina inferior derecha.
