Volver al inicio

Tkinter ToDo: filtros de búsqueda exportación CSV

El artículo describe la extensión de Tkinter ToDo: añadir Combobox para prioridades, filtrado con botones de radio, búsqueda en tiempo real y exportación CSV. Incluye código completo de métodos con manejo de UTF-8 y ordenación.

Filtros y exportación de datos en la aplicación Tkinter ToDo
Advertisement 728x90

# App ToDo con Tkinter: Filtros, búsqueda y exportación a CSV

Integrar la selección de prioridad directamente en el panel de entrada acelera la creación de tareas. Reemplazamos el diálogo modal con un ttk.Combobox que ofrece opciones de alta, media y baja prioridad. Permitir agregar con Enter optimiza el flujo de trabajo.

En create_widgets, agrega un frame con Entry, Combobox y botón:

from tkinter import ttk

top_frame = tk.Frame(self.root)
top_frame.pack(pady=10, padx=10, fill=tk.X)

self.entry = tk.Entry(top_frame, font=("Arial", 12))
self.entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
self.entry.bind("<Return>", lambda event: self.add_task())

tk.Label(top_frame, text="Prioridad:").pack(side=tk.LEFT, padx=(5, 2))
self.priority_var = tk.StringVar(value="medium")
priority_combo = ttk.Combobox(
    top_frame, 
    textvariable=self.priority_var, 
    values=["high", "medium", "low"],
    state="readonly",
    width=8
)
priority_combo.pack(side=tk.LEFT, padx=(0, 5))
priority_combo.set("medium")

self.add_button = tk.Button(top_frame, text="➕ Agregar", command=self.add_task, bg="light blue")
self.add_button.pack(side=tk.RIGHT)

El método add_task se simplifica: toma los datos de self.entry y self.priority_var.get(), guarda la tarea, limpia el campo y actualiza la lista.

Google AdInline article slot

Filtrado de tareas por estado

Botones de radio alternan las vistas: todas las tareas, solo activas o completadas. La lógica de filtro se integra en get_sorted_tasks.

En __init__, agrega self.filter_mode = "all". En create_widgets, añade un panel de filtros con Radiobuttons:

filter_frame = tk.Frame(self.root)
filter_frame.pack(pady=5, padx=10, fill=tk.X)

tk.Label(filter_frame, text="Filtro:").pack(side=tk.LEFT, padx=(0, 10))
self.filter_var = tk.StringVar(value="all")

tk.Radiobutton(filter_frame, text="Todas", variable=self.filter_var, 
               value="all", command=self.refresh_task_list).pack(side=tk.LEFT, padx=5)
tk.Radiobutton(filter_frame, text="Activas", variable=self.filter_var, 
               value="active", command=self.refresh_task_list).pack(side=tk.LEFT, padx=5)
tk.Radiobutton(filter_frame, text="Completadas", variable=self.filter_var, 
               value="completed", command=self.refresh_task_list).pack(side=tk.LEFT, padx=5)

En refresh_task_list: self.filter_mode = self.filter_var.get().

Google AdInline article slot

get_sorted_tasks filtra primero por estado, luego ordena las tareas activas por ID al principio y las completadas al final:

def get_sorted_tasks(self):
    if self.filter_mode == "active":
        filtered_tasks = [task for task in self.tasks if not task["completed"]]
    elif self.filter_mode == "completed":
        filtered_tasks = [task for task in self.tasks if task["completed"]]
    else:
        filtered_tasks = self.tasks.copy()
    
    active_tasks = [task for task in filtered_tasks if not task["completed"]]
    completed_tasks = [task for task in filtered_tasks if task["completed"]]
    
    active_tasks.sort(key=lambda x: x["id"])
    completed_tasks.sort(key=lambda x: x["id"])
    
    return active_tasks + completed_tasks

Búsqueda en tiempo real por texto de tarea

El campo de búsqueda con enlace <KeyRelease> permite filtrado instantáneo sobre el filtro de estado. El botón de limpiar reinicia la consulta.

En create_widgets, agrega search_frame:

Google AdInline article slot
search_frame = tk.Frame(self.root)
search_frame.pack(pady=(0, 5), padx=10, fill=tk.X)

tk.Label(search_frame, text="Buscar:").pack(side=tk.LEFT, padx=(0, 5))
self.search_entry = tk.Entry(search_frame, font=("Arial", 10))
self.search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.search_entry.bind("<KeyRelease>", lambda event: self.refresh_task_list())

clear_btn = tk.Button(search_frame, text="✖", command=self.clear_search, width=3)
clear_btn.pack(side=tk.RIGHT, padx=(5, 0))

clear_search limpia self.search_entry y llama a refresh_task_list.

get_sorted_tasks se expande con un segundo filtro por search_text = self.search_entry.get().strip().lower():

search_text = self.search_entry.get().strip().lower()
if search_text:
    filtered_tasks = [task for task in filtered_tasks if search_text in task["text"].lower()]

La búsqueda no distingue mayúsculas/minúsculas y se aplica después del filtrado por estado.

  • Ventajas de la búsqueda en tiempo real: Mínimo retraso usando comprensiones de listas.
  • Limitaciones: Búsqueda lineal O(n), ideal para <1000 tareas.
  • Optimización: Para listas grandes, considera bisect o indexación externa.

Exportación de datos filtrados a CSV

La exportación captura la vista actual de la lista (después de todos los filtros/búsqueda). Usa csv.writer con BOM UTF-8 para compatibilidad con Excel. Delimitador punto y coma, cabeceras: ID, Texto, Estado, Prioridad, Fecha creación.

Botón en bottom_frame:

self.export_button = tk.Button(bottom_frame, text="📎 Exportar a CSV", command=self.export_to_csv, bg="light cyan")
self.export_button.pack(side=tk.LEFT, padx=5)

export_to_csv:

import csv
from tkinter import filedialog

def export_to_csv(self):
    tasks_to_export = self.get_sorted_tasks()
    if not tasks_to_export:
        messagebox.showinfo("Info", "No hay tareas para exportar")
        return
    
    filename = filedialog.asksaveasfilename(
        defaultextension=".csv",
        filetypes=[("Archivos CSV", "*.csv"), ("Todos los archivos", "*.*")],
        title="Guardar como CSV"
    )
    if not filename:
        return
    
    try:
        with open(filename, 'w', encoding='utf-8-sig', newline='') as f:
            writer = csv.writer(f, delimiter=';')
            writer.writerow(['ID', 'Texto', 'Estado', 'Prioridad', 'Creada'])
            
            for task in tasks_to_export:
                status = "Completada" if task["completed"] else "Activa"
                try:
                    created = datetime.fromisoformat(task["created_at"])
                    date_str = created.strftime("%d.%m.%Y %H:%M:%S")
                except:
                    date_str = task["created_at"]
                priority_map = {"high": "Alta", "medium": "Media", "low": "Baja"}
                priority_display = priority_map.get(task["priority"], task["priority"])
                
                writer.writerow([task["id"], task["text"], status, priority_display, date_str])
        
        messagebox.showinfo("Éxito", f"Tareas exportadas a:\n{filename}")
    except Exception as e:
        messagebox.showerror("Error", f"Error al guardar archivo: {e}")

Lecciones clave

  • Integración de Combobox para prioridades simplifica la UX sin popups.
  • Filtrado combinado (estado + búsqueda) aprovecha comprensiones de listas encadenadas para velocidad.
  • Exportación CSV con UTF-8-sig y ';' funciona perfectamente con Excel en Windows.
  • Actualizaciones en tiempo real vía enlaces <KeyRelease> y comandos de Radiobutton.
  • Ordenación siempre prioriza tareas activas arriba.

— Editorial Team

Advertisement 728x90

Leer después