# Confirmación

> Una pregunta de sí o no, en rojo para acciones destructivas. Componente de Pyzed para GUIs de escritorio en Python, con ejemplos y API.

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

:::tip[En pocas palabras]
Pregunta “¿seguro?” antes de hacer algo que no se puede deshacer.
:::

Hace una pregunta de sí o no. `danger=True` pinta de rojo el botón de confirmar; `confirm_label` y `cancel_label` cambian el texto de los botones.

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

**Código:**

```python
ui.dialog_layer(main_view(), ui.confirm(
    "Delete notes.py? This can't be undone.", on_delete, on_cancel,
    title="Delete file", danger=True, confirm_label="Delete", 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

- Antes de acciones destructivas o irreversibles: borrar, sobrescribir, descartar.

## Uso

```python
from pyzed import ui

ui.dialog_layer(main_view(), ui.confirm(
    "Delete notes.py? This can't be undone.", on_delete, on_cancel,
    title="Delete file", danger=True, confirm_label="Delete", 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.confirm("Close all tabs?", on_confirm, on_cancel, title="Close tabs", width=320)
```

```python
ui.confirm("Delete notes.py?", on_delete, on_cancel, title="Delete file", danger=True,
           confirm_label="Delete", width=320)
```

```python
ui.confirm("Overwrite the existing file?", on_confirm, on_cancel, kind="warning", width=320)
```

```python
ui.confirm("Push 3 commits to main?", on_push, on_cancel, confirm_label="Push",
           cancel_label="Not now", width=320)
```

## Eventos

Confirmación tiene **2 eventos 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_confirm` | `()` | El botón de confirmar. |
| `on_cancel` | `()` | Cancelar, 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 Files(pz.App):
    def __init__(self):
        self.files = ["notes.py", "todo.txt"]
        self.deleting = "notes.py"       # the file waiting for an answer

    def delete(self):                    # on_confirm
        self.files.remove(self.deleting)
        self.deleting = None

    def view(self):
        dialog = None
        if self.deleting:
            dialog = ui.confirm(f"Delete {self.deleting}?", self.delete,
                                lambda: setattr(self, "deleting", None),   # on_cancel
                                title="Delete file", danger=True, confirm_label="Delete")
        return ui.dialog_layer(main_view(), dialog)
```

**Declarativo:**

```python
from dataclasses import dataclass

@dataclass
class Delete:
    name: str

class Files(pz.App):
    files = ["notes.py", "todo.txt"]
    deleting = "notes.py"

    def update(self, message):
        match message:
            case Delete(name):
                self.files = [f for f in self.files if f != name]
                self.deleting = None
            case "cancel":
                self.deleting = None

    def view(self):
        dialog = ui.confirm(f"Delete {self.deleting}?", Delete(self.deleting), "cancel", danger=True) \
            if self.deleting else None
        return ui.dialog_layer(main_view(), dialog)
```

**Funcional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    files: tuple = ("notes.py", "todo.txt")
    deleting: str = "notes.py"

def view(state, set_state):
    if not state.deleting:
        return main_view()
    keep = tuple(f for f in state.files if f != state.deleting)
    return ui.dialog_layer(main_view(), ui.confirm(
        f"Delete {state.deleting}?", lambda: set_state(files=keep, deleting=""),
        lambda: set_state(deleting=""), danger=True))
```

## Propiedades y API

### `ui.confirm`

```python
confirm(
    message,
    on_confirm,
    on_cancel,
    *,
    title=None,
    confirm_label=None,
    cancel_label=None,
    danger=False,
    kind=None,
    width=420,
    theme=None,
)
```

Hace una pregunta de sí o no.

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `message` | *obligatorio* | Texto o widget. |
| `title` | `None` | Título. |
| `confirm_label` | `None` | Texto del botón de confirmar. |
| `cancel_label` | `None` | Texto del botón de cancelar. |
| `danger` | `False` | Pinta el botón de rojo y lo llama Eliminar. |
| `kind` | `None` | Añade un icono, como en `alert`. |
| `width` | `420` | Ancho: píxeles, `"fill"`, `"shrink"` o `"fill:N"` (proporción). |
| `theme` | `None` | Tema a usar en lugar del actual (`pyzed.theme.current()`). |

Eventos: `on_confirm`, `on_cancel` ([eventos](#eventos)).

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

## Relacionados

- [Alerta](https://albakore.github.io/pyzed/es/library/alert/): Un mensaje con un botón.
- [Elección](https://albakore.github.io/pyzed/es/library/choice/): Un mensaje con tus propios botones.
- [Cambios sin guardar](https://albakore.github.io/pyzed/es/library/unsaved-changes/): “¿Guardar los cambios antes de cerrar?”
