Back to Home

Tkinter ToDo: search filters CSV export

The article describes the extension of Tkinter ToDo: adding Combobox for priorities, radio buttons filtering, real-time search and CSV export. Includes full code of methods with UTF-8 handling and sorting.

Filters and data export in Tkinter ToDo application
Advertisement 728x90

Tkinter ToDo App: Filters, Search, and CSV Export

Integrating priority selection directly into the input panel speeds up task creation. We replace the modal dialog with a ttk.Combobox offering high, medium, and low options. Enabling add-on-Enter streamlines the workflow.

In create_widgets, add a frame with Entry, Combobox, and button:

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="Priority:").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="➕ Add", command=self.add_task, bg="light blue")
self.add_button.pack(side=tk.RIGHT)

The add_task method simplifies: grabs data from self.entry and self.priority_var.get(), saves the task, clears the field, and refreshes the list.

Google AdInline article slot

Filtering Tasks by Status

Radio buttons toggle views: all tasks, active only, or completed. Filter logic integrates into get_sorted_tasks.

In __init__, add self.filter_mode = "all". In create_widgets, add a filter panel with Radiobuttons:

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

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

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

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

Google AdInline article slot

get_sorted_tasks first filters by status, then sorts active tasks by ID at the top, completed at the bottom:

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

Real-Time Search by Task Text

Search field with <KeyRelease> binding enables instant filtering on top of the status filter. Clear button resets the query.

In create_widgets, add 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="Search:").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 clears self.search_entry and calls refresh_task_list.

get_sorted_tasks expands with a second filter by 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()]

Search is case-insensitive and applies after status filtering.

  • Real-time search perks: Minimal lag using list comprehensions.
  • Limitations: Linear O(n) search, fine for <1000 tasks.
  • Optimization: For larger lists, consider bisect or external indexing.

Exporting Filtered Data to CSV

Export captures the current list view (after all filters/search). Uses csv.writer with UTF-8 BOM for Excel compatibility. Semicolon delimiter, headers: ID, Text, Status, Priority, Created Date.

Button in bottom_frame:

self.export_button = tk.Button(bottom_frame, text="📎 Export to 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 tasks to export")
        return
    
    filename = filedialog.asksaveasfilename(
        defaultextension=".csv",
        filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
        title="Save as 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', 'Text', 'Status', 'Priority', 'Created'])
            
            for task in tasks_to_export:
                status = "Completed" if task["completed"] else "Active"
                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": "High", "medium": "Medium", "low": "Low"}
                priority_display = priority_map.get(task["priority"], task["priority"])
                
                writer.writerow([task["id"], task["text"], status, priority_display, date_str])
        
        messagebox.showinfo("Success", f"Tasks exported to:\n{filename}")
    except Exception as e:
        messagebox.showerror("Error", f"Failed to save file: {e}")

Key Takeaways

  • Combobox integration for priorities simplifies UX without popups.
  • Combined filtering (status + search) leverages chained list comprehensions for speed.
  • CSV export with UTF-8-sig and ';' works seamlessly with Excel on Windows.
  • Real-time updates via <KeyRelease> binds and Radiobutton commands.
  • Sorting always prioritizes active tasks at the top.

— Editorial Team

Advertisement 728x90

Read Next