The user wants a Python GUI application for task/todo list management. I'll create a comprehensive task manager with the following features:
-
Core Features:
- Add, edit, delete tasks
- Mark tasks as complete/incomplete
- Set priority levels (High, Medium, Low)
- Set due dates
- Categories/tags for organization
- Search and filter tasks
-
GUI Elements:
- Main task list view
- Add/Edit task dialog
- Filter panel
- Statistics/progress overview
- Visual indicators for priority and status
-
Technical Implementation:
- Use Tkinter (built-in, no external dependencies needed for GUI)
- SQLite for data persistence
- Clean, modern interface with custom styling
- Sorting capabilities
Let me create a comprehensive, professional-looking task manager application.
Python Task Manager Application
A comprehensive GUI-based task management application with a modern interface, task prioritization, categories, due dates, and data persistence.
Installation
pip install tkcalendar
Note: tkinter comes pre-installed with Python on most systems. If you're on Linux and it's missing, install it with:
sudo apt-get install python3-tk # Debian/Ubuntu
Complete Code
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from tkcalendar import DateEntry
from datetime import datetime, date
import sqlite3
import json
import os
from typing import Optional, List, Dict
class DatabaseManager:
"""Handles all database operations for task management."""
def __init__(self, db_path: str = "tasks.db"):
self.db_path = db_path
self.init_database()
def get_connection(self) -> sqlite3.Connection:
return sqlite3.connect(self.db_path)
def init_database(self):
"""Initialize the database with required tables."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
priority TEXT DEFAULT 'Medium',
category TEXT DEFAULT 'General',
due_date TEXT,
created_date TEXT NOT NULL,
completed INTEGER DEFAULT 0,
completed_date TEXT
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
color TEXT DEFAULT '#3498db'
)
''')
# Insert default categories if not exist
default_categories = [
('General', '#3498db'),
('Work', '#e74c3c'),
('Personal', '#2ecc71'),
('Shopping', '#f39c12'),
('Health', '#9b59b6')
]
for name, color in default_categories:
cursor.execute('''
INSERT OR IGNORE INTO categories (name, color) VALUES (?, ?)
''', (name, color))
conn.commit()
conn.close()
def add_task(self, title: str, description: str, priority: str,
category: str, due_date: str) -> int:
"""Add a new task to the database."""
conn = self.get_connection()
cursor = conn.cursor()
created_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('''
INSERT INTO tasks (title, description, priority, category, due_date, created_date)
VALUES (?, ?, ?, ?, ?, ?)
''', (title, description, priority, category, due_date, created_date))
task_id = cursor.lastrowid
conn.commit()
conn.close()
return task_id
def update_task(self, task_id: int, title: str, description: str,
priority: str, category: str, due_date: str):
"""Update an existing task."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
UPDATE tasks
SET title=?, description=?, priority=?, category=?, due_date=?
WHERE id=?
''', (title, description, priority, category, due_date, task_id))
conn.commit()
conn.close()
def delete_task(self, task_id: int):
"""Delete a task from the database."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('DELETE FROM tasks WHERE id=?', (task_id,))
conn.commit()
conn.close()
def toggle_task_completion(self, task_id: int, completed: bool):
"""Toggle task completion status."""
conn = self.get_connection()
cursor = conn.cursor()
completed_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if completed else None
cursor.execute('''
UPDATE tasks SET completed=?, completed_date=? WHERE id=?
''', (1 if completed else 0, completed_date, task_id))
conn.commit()
conn.close()
def get_all_tasks(self) -> List[Dict]:
"""Retrieve all tasks from the database."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT id, title, description, priority, category, due_date,
created_date, completed, completed_date
FROM tasks
ORDER BY
CASE priority
WHEN 'High' THEN 1
WHEN 'Medium' THEN 2
WHEN 'Low' THEN 3
END,
due_date ASC
''')
tasks = []
for row in cursor.fetchall():
tasks.append({
'id': row[0],
'title': row[1],
'description': row[2],
'priority': row[3],
'category': row[4],
'due_date': row[5],
'created_date': row[6],
'completed': bool(row[7]),
'completed_date': row[8]
})
conn.close()
return tasks
def get_tasks_by_filter(self, category: str = None, priority: str = None,
completed: bool = None, search: str = None) -> List[Dict]:
"""Get tasks with optional filters."""
conn = self.get_connection()
cursor = conn.cursor()
query = '''
SELECT id, title, description, priority, category, due_date,
created_date, completed, completed_date
FROM tasks
WHERE 1=1
'''
params = []
if category and category != "All":
query += ' AND category=?'
params.append(category)
if priority and priority != "All":
query += ' AND priority=?'
params.append(priority)
if completed is not None:
query += ' AND completed=?'
params.append(1 if completed else 0)
if search:
query += ' AND (title LIKE ? OR description LIKE ?)'
params.extend([f'%{search}%', f'%{search}%'])
query += '''
ORDER BY
CASE priority
WHEN 'High' THEN 1
WHEN 'Medium' THEN 2
WHEN 'Low' THEN 3
END,
due_date ASC
'''
cursor.execute(query, params)
tasks = []
for row in cursor.fetchall():
tasks.append({
'id': row[0],
'title': row[1],
'description': row[2],
'priority': row[3],
'category': row[4],
'due_date': row[5],
'created_date': row[6],
'completed': bool(row[7]),
'completed_date': row[8]
})
conn.close()
return tasks
def get_categories(self) -> List[Dict]:
"""Get all categories."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('SELECT name, color FROM categories ORDER BY name')
categories = [{'name': row[0], 'color': row[1]} for row in cursor.fetchall()]
conn.close()
return categories
def add_category(self, name: str, color: str = '#3498db'):
"""Add a new category."""
conn = self.get_connection()
cursor = conn.cursor()
try:
cursor.execute('INSERT INTO categories (name, color) VALUES (?, ?)', (name, color))
conn.commit()
conn.close()
return True
except sqlite3.IntegrityError:
conn.close()
return False
def get_statistics(self) -> Dict:
"""Get task statistics."""
conn = self.get_connection()
cursor = conn.cursor()
stats = {}
# Total tasks
cursor.execute('SELECT COUNT(*) FROM tasks')
stats['total'] = cursor.fetchone()[0]
# Completed tasks
cursor.execute('SELECT COUNT(*) FROM tasks WHERE completed=1')
stats['completed'] = cursor.fetchone()[0]
# Pending tasks
stats['pending'] = stats['total'] - stats['completed']
# Overdue tasks
today = date.today().strftime("%Y-%m-%d")
cursor.execute('''
SELECT COUNT(*) FROM tasks
WHERE completed=0 AND due_date < ? AND due_date IS NOT NULL
''', (today,))
stats['overdue'] = cursor.fetchone()[0]
# High priority pending
cursor.execute('SELECT COUNT(*) FROM tasks WHERE completed=0 AND priority="High"')
stats['high_priority'] = cursor.fetchone()[0]
conn.close()
return stats
class TaskDialog(tk.Toplevel):
"""Dialog for adding/editing tasks."""
def __init__(self, parent, db_manager: DatabaseManager, task: Dict = None):
super().__init__(parent)
self.db = db_manager
self.task = task
self.result = None
self.title("Add Task" if task is None else "Edit Task")
self.geometry("450x400")
self.resizable(False, False)
self.configure(bg='#f5f6fa')
# Make dialog modal
self.transient(parent)
self.grab_set()
# Center the dialog
self.update_idletasks()
x = parent.winfo_x() + (parent.winfo_width() - self.winfo_width()) // 2
y = parent.winfo_y() + (parent.winfo_height() - self.winfo_height()) // 2
self.geometry(f"+{x}+{y}")
self.create_widgets()
# Focus on title entry
self.title_entry.focus_set()
# Bind Enter key to save
self.bind('<Return>', lambda e: self.save_task())
self.bind('<Escape>', lambda e: self.destroy())
def create_widgets(self):
# Main frame
main_frame = ttk.Frame(self, padding=20)
main_frame.pack(fill=tk.BOTH, expand=True)
# Title
ttk.Label(main_frame, text="Title:", font=('Segoe UI', 10, 'bold')).grid(
row=0, column=0, sticky='w', pady=(0, 5))
self.title_entry = ttk.Entry(main_frame, width=45, font=('Segoe UI', 10))
self.title_entry.grid(row=1, column=0, columnspan=2, sticky='ew', pady=(0, 15))
# Description
ttk.Label(main_frame, text="Description:", font=('Segoe UI', 10, 'bold')).grid(
row=2, column=0, sticky='w', pady=(0, 5))
self.desc_text = tk.Text(main_frame, height=4, width=45, font=('Segoe UI', 10),
wrap=tk.WORD, relief='solid', borderwidth=1)
self.desc_text.grid(row=3, column=0, columnspan=2, sticky='ew', pady=(0, 15))
# Priority and Category frame
options_frame = ttk.Frame(main_frame)
options_frame.grid(row=4, column=0, columnspan=2, sticky='ew', pady=(0, 15))
# Priority
ttk.Label(options_frame, text="Priority:", font=('Segoe UI', 10, 'bold')).grid(
row=0, column=0, sticky='w', pady=(0, 5))
self.priority_var = tk.StringVar(value='Medium')
priority_combo = ttk.Combobox(options_frame, textvariable=self.priority_var,
values=['High', 'Medium', 'Low'], state='readonly', width=15)
priority_combo.grid(row=1, column=0, sticky='w', padx=(0, 20))
# Category
ttk.Label(options_frame, text="Category:", font=('Segoe UI', 10, 'bold')).grid(
row=0, column=1, sticky='w', pady=(0, 5))
categories = [cat['name'] for cat in self.db.get_categories()]
self.category_var = tk.StringVar(value=categories[0] if categories else 'General')
category_combo = ttk.Combobox(options_frame, textvariable=self.category_var,
values=categories, state='readonly', width=15)
category_combo.grid(row=1, column=1, sticky='w')
# Due Date
ttk.Label(main_frame, text="Due Date:", font=('Segoe UI', 10, 'bold')).grid(
row=5, column=0, sticky='w', pady=(0, 5))
date_frame = ttk.Frame(main_frame)
date_frame.grid(row=6, column=0, columnspan=2, sticky='ew', pady=(0, 20))
self.no_due_date_var = tk.BooleanVar(value=True)
no_due_date_check = ttk.Checkbutton(date_frame, text="No due date",
variable=self.no_due_date_var,
command=self.toggle_date_picker)
no_due_date_check.pack(side=tk.LEFT)
self.date_picker = DateEntry(date_frame, width=15, date_pattern='yyyy-mm-dd',
state='disabled')
self.date_picker.pack(side=tk.LEFT, padx=(10, 0))
# Buttons
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=7, column=0, columnspan=2, sticky='ew')
save_btn = tk.Button(button_frame, text="Save", command=self.save_task,
bg='#3498db', fg='white', font=('Segoe UI', 10, 'bold'),
width=12, cursor='hand2', relief='flat')
save_btn.pack(side=tk.LEFT, padx=(0, 10))
cancel_btn = tk.Button(button_frame, text="Cancel", command=self.destroy,
bg='#e74c3c', fg='white', font=('Segoe UI', 10, 'bold'),
width=12, cursor='hand2', relief='flat')
cancel_btn.pack(side=tk.LEFT)
# Load task data if editing
if self.task:
self.load_task_data()
def toggle_date_picker(self):
if self.no_due_date_var.get():
self.date_picker.configure(state='disabled')
else:
self.date_picker.configure(state='normal')
def load_task_data(self):
self.title_entry.insert(0, self.task['title'])
self.desc_text.insert('1.0', self.task['description'] or '')
self.priority_var.set(self.task['priority'])
self.category_var.set(self.task['category'])
if self.task['due_date']:
self.no_due_date_var.set(False)
self.date_picker.configure(state='normal')
self.date_picker.set_date(self.task['due_date'])
def save_task(self):
title = self.title_entry.get().strip()
if not title:
messagebox.showwarning("Validation Error", "Task title is required!", parent=self)
return
description = self.desc_text.get('1.0', 'end-1c').strip()
priority = self.priority_var.get()
category = self.category_var.get()
due_date = '' if self.no_due_date_var.get() else self.date_picker.get()
self.result = {
'title': title,
'description': description,
'priority': priority,
'category': category,
'due_date': due_date
}
self.destroy()
class TaskManagerApp:
"""Main Task Manager Application."""
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("📋 Task Manager Pro")
self.root.geometry("1100x700")
self.root.minsize(900, 600)
# Configure root window
self.root.configure(bg='#ecf0f1')
# Initialize database
self.db = DatabaseManager()
# Configure styles
self.configure_styles()
# Create UI
self.create_ui()
# Load tasks
self.refresh_tasks()
# Bind events
self.root.bind('<Control-n>', lambda e: self.add_task())
self.root.bind('<Delete>', lambda e: self.delete_task())
self.root.bind('<F5>', lambda e: self.refresh_tasks())
def configure_styles(self):
"""Configure ttk styles for modern appearance."""
style = ttk.Style()
style.theme_use('clam')
# Frame styles
style.configure('Main.TFrame', background='#ecf0f1')
style.configure('Card.TFrame', background='white')
style.configure('Sidebar.TFrame', background='#2c3e50')
# Label styles
style.configure('Title.TLabel', font=('Segoe UI', 24, 'bold'),
foreground='#2c3e50', background='#ecf0f1')
style.configure('Subtitle.TLabel', font=('Segoe UI', 11),
foreground='#7f8c8d', background='#ecf0f1')
style.configure('Stats.TLabel', font=('Segoe UI', 10),
foreground='#2c3e50', background='white')
style.configure('StatsNumber.TLabel', font=('Segoe UI', 20, 'bold'),
foreground='#3498db', background='white')
style.configure('Sidebar.TLabel', font=('Segoe UI', 10),
foreground='#ecf0f1', background='#2c3e50')
# Button styles
style.configure('Primary.TButton', font=('Segoe UI', 10, 'bold'), padding=10)
style.configure('Sidebar.TButton', font=('Segoe UI', 10), padding=8,
foreground='#ecf0f1', background='#34495e')
# Treeview styles
style.configure('Task.Treeview', font=('Segoe UI', 10), rowheight=40)
style.configure('Task.Treeview.Heading', font=('Segoe UI', 10, 'bold'))
# Entry styles
style.configure('Search.TEntry', font=('Segoe UI', 10), padding=5)
# Combobox styles
style.configure('Filter.TCombobox', font=('Segoe UI', 10), padding=5)
def create_ui(self):
"""Create the main user interface."""
# Main container
main_container = ttk.Frame(self.root, style='Main.TFrame')
main_container.pack(fill=tk.BOTH, expand=True)
# Create sidebar
self.create_sidebar(main_container)
# Create main content area
self.create_main_content(main_container)
def create_sidebar(self, parent):
"""Create the sidebar with statistics and quick actions."""
sidebar = ttk.Frame(parent, style='Sidebar.TFrame', width=250)
sidebar.pack(side=tk.LEFT, fill=tk.Y)
sidebar.pack_propagate(False)
# App title
title_frame = ttk.Frame(sidebar, style='Sidebar.TFrame')
title_frame.pack(fill=tk.X, pady=20, padx=15)
ttk.Label(title_frame, text="📋 Task Manager", style='Sidebar.TLabel',
font=('Segoe UI', 16, 'bold')).pack(anchor='w')
ttk.Label(title_frame, text="Stay organized, stay productive",
style='Sidebar.TLabel', font=('Segoe UI', 9)).pack(anchor='w')
# Statistics section
stats_frame = ttk.Frame(sidebar, style='Sidebar.TFrame')
stats_frame.pack(fill=tk.X, pady=20, padx=15)
ttk.Label(stats_frame, text="📊 Statistics", style='Sidebar.TLabel',
font=('Segoe UI', 12, 'bold')).pack(anchor='w', pady=(0, 10))
# Stats cards
self.stats_labels = {}
stats_items = [
('total', 'Total Tasks', '#3498db'),
('completed', 'Completed', '#2ecc71'),
('pending', 'Pending', '#f39c12'),
('overdue', 'Overdue', '#e74c3c'),
('high_priority', 'High Priority', '#9b59b6')
]
for key, label, color in stats_items:
card = tk.Frame(stats_frame, bg='#34495e', padx=10, pady=8)
card.pack(fill=tk.X, pady=3)
tk.Label(card, text=label, font=('Segoe UI', 9),
fg='#bdc3c7', bg='#34495e').pack(anchor='w')
num_label = tk.Label(card, text="0", font=('Segoe UI', 16, 'bold'),
fg=color, bg='#34495e')
num_label.pack(anchor='w')
self.stats_labels[key] = num_label
# Quick actions
actions_frame = ttk.Frame(sidebar, style='Sidebar.TFrame')
actions_frame.pack(fill=tk.X, pady=20, padx=15)
ttk.Label(actions_frame, text="⚡ Quick Actions", style='Sidebar.TLabel',
font=('Segoe UI', 12, 'bold')).pack(anchor='w', pady=(0, 10))
add_btn = tk.Button(actions_frame, text="➕ Add New Task",
command=self.add_task, bg='#3498db', fg='white',
font=('Segoe UI', 10), cursor='hand2', relief='flat',
activebackground='#2980b9', activeforeground='white')
add_btn.pack(fill=tk.X, pady=3)
refresh_btn = tk.Button(actions_frame, text="🔄 Refresh Tasks",
command=self.refresh_tasks, bg='#34495e', fg='white',
font=('Segoe UI', 10), cursor='hand2', relief='flat',
activebackground='#2c3e50', activeforeground='white')
refresh_btn.pack(fill=tk.X, pady=3)
clear_completed_btn = tk.Button(actions_frame, text="🗑️ Clear Completed",
command=self.clear_completed, bg='#34495e', fg='white',
font=('Segoe UI', 10), cursor='hand2', relief='flat',
activebackground='#2c3e50', activeforeground='white')
clear_completed_btn.pack(fill=tk.X, pady=3)
def create_main_content(self, parent):
"""Create the main content area with task list."""
main_frame = ttk.Frame(parent, style='Main.TFrame')
main_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=20, pady=20)
# Header
header_frame = ttk.Frame(main_frame, style='Main.TFrame')
header_frame.pack(fill=tk.X, pady=(0, 20))
ttk.Label(header_frame, text="My Tasks", style='Title.TLabel').pack(side=tk.LEFT)
# Search and filters
filter_frame = ttk.Frame(main_frame, style='Main.TFrame')
filter_frame.pack(fill=tk.X, pady=(0, 15))
# Search box
search_frame = ttk.Frame(filter_frame, style='Main.TFrame')
search_frame.pack(side=tk.LEFT, fill=tk.X, expand=True)
ttk.Label(search_frame, text="🔍", style='Subtitle.TLabel').pack(side=tk.LEFT)
self.search_var = tk.StringVar()
self.search_var.trace('w', self.on_search_change)
search_entry = ttk.Entry(search_frame, textvariable=self.search_var,
style='Search.TEntry', width=30)
search_entry.pack(side=tk.LEFT, padx=(5, 20))
search_entry.insert(0, "Search tasks...")
search_entry.bind('<FocusIn>', self.on_search_focus_in)
search_entry.bind('<FocusOut>', self.on_search_focus_out)
# Filters
ttk.Label(filter_frame, text="Priority:", style='Subtitle.TLabel').pack(side=tk.LEFT)
self.priority_filter = tk.StringVar(value="All")
priority_combo = ttk.Combobox(filter_frame, textvariable=self.priority_filter,
values=["All", "High", "Medium", "Low"],
state='readonly', width=10, style='Filter.TCombobox')
priority_combo.pack(side=tk.LEFT, padx=(5, 15))
priority_combo.bind('<<ComboboxSelected>>', self.on_filter_change)
ttk.Label(filter_frame, text="Category:", style='Subtitle.TLabel').pack(side=tk.LEFT)
self.category_filter = tk.StringVar(value="All")
self.category_combo = ttk.Combobox(filter_frame, textvariable=self.category_filter,
values=["All"], state='readonly', width=12,
style='Filter.TCombobox')
self.category_combo.pack(side=tk.LEFT, padx=(5, 15))
self.category_combo.bind('<<ComboboxSelected>>', self.on_filter_change)
ttk.Label(filter_frame, text="Status:", style='Subtitle.TLabel').pack(side=tk.LEFT)
self.status_filter = tk.StringVar(value="All")
status_combo = ttk.Combobox(filter_frame, textvariable=self.status_filter,
values=["All", "Pending", "Completed"],
state='readonly', width=10, style='Filter.TCombobox')
status_combo.pack(side=tk.LEFT, padx=(5, 0))
status_combo.bind('<<ComboboxSelected>>', self.on_filter_change)
# Task list
list_frame = tk.Frame(main_frame, bg='white', relief='flat')
list_frame.pack(fill=tk.BOTH, expand=True)
# Treeview with scrollbar
columns = ('status', 'title', 'priority', 'category', 'due_date', 'created')
self.task_tree = ttk.Treeview(list_frame, columns=columns, show='headings',
style='Task.Treeview', selectmode='browse')
# Configure columns
self.task_tree.heading('status', text='✓')
self.task_tree.heading('title', text='Task')
self.task_tree.heading('priority', text='Priority')
self.task_tree.heading('category', text='Category')
self.task_tree.heading('due_date', text='Due Date')
self.task_tree.heading('created', text='Created')
self.task_tree.column('status', width=50, minwidth=50, anchor='center')
self.task_tree.column('title', width=350, minwidth=200)
self.task_tree.column('priority', width=100, minwidth=80, anchor='center')
self.task_tree.column('category', width=120, minwidth=100, anchor='center')
self.task_tree.column('due_date', width=120, minwidth=100, anchor='center')
self.task_tree.column('created', width=120, minwidth=100, anchor='center')
# Scrollbar
scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.task_tree.yview)
self.task_tree.configure(yscrollcommand=scrollbar.set)
self.task_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Configure tags for row colors
self.task_tree.tag_configure('completed', foreground='#95a5a6')
self.task_tree.tag_configure('overdue', foreground='#e74c3c')
self.task_tree.tag_configure('high_priority', foreground='#e74c3c')
self.task_tree.tag_configure('even', background='#f8f9fa')
self.task_tree.tag_configure('odd', background='white')
# Bind events
self.task_tree.bind('<Double-1>', self.on_task_double_click)
self.task_tree.bind('<Button-3>', self.show_context_menu)
# Action buttons at bottom
button_frame = ttk.Frame(main_frame, style='Main.TFrame')
button_frame.pack(fill=tk.X, pady=(15, 0))
edit_btn = tk.Button(button_frame, text="✏️ Edit", command=self.edit_task,
bg='#3498db', fg='white', font=('Segoe UI', 10),
cursor='hand2', relief='flat', width=12)
edit_btn.pack(side=tk.LEFT, padx=(0, 10))
delete_btn = tk.Button(button_frame, text="🗑️ Delete", command=self.delete_task,
bg='#e74c3c', fg='white', font=('Segoe UI', 10),
cursor='hand2', relief='flat', width=12)
delete_btn.pack(side=tk.LEFT, padx=(0, 10))
toggle_btn = tk.Button(button_frame, text="✓ Toggle Complete",
command=self.toggle_task_completion,
bg='#2ecc71', fg='white', font=('Segoe UI', 10),
cursor='hand2', relief='flat', width=14)
toggle_btn.pack(side=tk.LEFT)
# Update category combo
self.update_category_filters()
def update_category_filters(self):
"""Update the category filter combobox."""
categories = ['All'] + [cat['name'] for cat in self.db.get_categories()]
self.category_combo['values'] = categories
def on_search_focus_in(self, event):
if self.search_var.get() == "Search tasks...":
self.search_var.set("")
def on_search_focus_out(self, event):
if not self.search_var.get():
self.search_var.set("Search tasks...")
def on_search_change(self, *args):
search_term = self.search_var.get()
if search_term and search_term != "Search tasks...":
self.refresh_tasks()
def on_filter_change(self, event=None):
self.refresh_tasks()
def refresh_tasks(self):
"""Refresh the task list from database."""
# Clear existing items
for item in self.task_tree.get_children():
self.task_tree.delete(item)
# Get filter values
priority = self.priority_filter.get()
category = self.category_filter.get()
status = self.status_filter.get()
search = self.search_var.get()
if search == "Search tasks...":
search = None
# Get completed filter
completed = None
if status == "Pending":
completed = False
elif status == "Completed":
completed = True
# Fetch tasks
tasks = self.db.get_tasks_by_filter(
category=category if category != "All" else None,
priority=priority if priority != "All" else None,
completed=completed,
search=search
)
# Populate treeview
today = date.today()
for idx, task in enumerate(tasks):
status_icon = "✅" if task['completed'] else "⬜"
priority_icon = {"High": "🔴", "Medium": "🟡", "Low": "🟢"}.get(task['priority'], "⚪")
due_date = task['due_date'] or "No date"
# Check if overdue
is_overdue = False
if task['due_date'] and not task['completed']:
try:
due = datetime.strptime(task['due_date'], "%Y-%m-%d").date()
is_overdue = due < today
except:
pass
tags = []
if task['completed']:
tags.append('completed')
elif is_overdue:
tags.append('overdue')
elif task['priority'] == 'High':
tags.append('high_priority')
tags.append('even' if idx % 2 == 0 else 'odd')
self.task_tree.insert('', 'end', iid=task['id'], values=(
status_icon,
task['title'],
f"{priority_icon} {task['priority']}",
task['category'],
due_date,
task['created_date'].split()[0] if task['created_date'] else ""
), tags=tags)
# Update statistics
self.update_statistics()
# Update category filters
self.update_category_filters()
def update_statistics(self):
"""Update the statistics display."""
stats = self.db.get_statistics()
for key, label in self.stats_labels.items():
label.configure(text=str(stats.get(key, 0)))
def add_task(self):
"""Open dialog to add a new task."""
dialog = TaskDialog(self.root, self.db)
self.root.wait_window(dialog)
if dialog.result:
self.db.add_task(
title=dialog.result['title'],
description=dialog.result['description'],
priority=dialog.result['priority'],
category=dialog.result['category'],
due_date=dialog.result['due_date']
)
self.refresh_tasks()
def edit_task(self):
"""Edit the selected task."""
selection = self.task_tree.selection()
if not selection:
messagebox.showinfo("Info", "Please select a task to edit.")
return
task_id = int(selection[0])
# Get task data
tasks = self.db.get_all_tasks()
task = next((t for t in tasks if t['id'] == task_id), None)
if task:
dialog = TaskDialog(self.root, self.db, task)
self.root.wait_window(dialog)
if dialog.result:
self.db.update_task(
task_id=task_id,
title=dialog.result['title'],
description=dialog.result['description'],
priority=dialog.result['priority'],
category=dialog.result['category'],
due_date=dialog.result['due_date']
)
self.refresh_tasks()
def delete_task(self):
"""Delete the selected task."""
selection = self.task_tree.selection()
if not selection:
messagebox.showinfo("Info", "Please select a task to delete.")
return
task_id = int(selection[0])
# Get task title for confirmation
item = self.task_tree.item(selection[0])
task_title = item['values'][1]
if messagebox.askyesno("Confirm Delete",
f"Are you sure you want to delete:\n{task_title}?"):
self.db.delete_task(task_id)
self.refresh_tasks()
def toggle_task_completion(self):
"""Toggle the completion status of selected task."""
selection = self.task_tree.selection()
if not selection:
messagebox.showinfo("Info", "Please select a task to toggle.")
return
task_id = int(selection[0])
# Get current status
tasks = self.db.get_all_tasks()
task = next((t for t in tasks if t['id'] == task_id), None)
if task:
new_status = not task['completed']
self.db.toggle_task_completion(task_id, new_status)
self.refresh_tasks()
def clear_completed(self):
"""Clear all completed tasks."""
if messagebox.askyesno("Confirm", "Delete all completed tasks?"):
tasks = self.db.get_all_tasks()
for task in tasks:
if task['completed']:
self.db.delete_task(task['id'])
self.refresh_tasks()
def on_task_double_click(self, event):
"""Handle double-click on task."""
self.edit_task()
def show_context_menu(self, event):
"""Show context menu on right-click."""
# Select item under cursor
item = self.task_tree.identify_row(event.y)
if item:
self.task_tree.selection_set(item)
menu = tk.Menu(self.root, tearoff=0)
menu.add_command(label="✏️ Edit", command=self.edit_task)
menu.add_command(label="✓ Toggle Complete", command=self.toggle_task_completion)
menu.add_separator()
menu.add_command(label="🗑️ Delete", command=self.delete_task)
menu.post(event.x_root, event.y_root)
def main():
"""Main entry point."""
root = tk.Tk()
# Set icon if available
try:
root.iconbitmap('icon.ico')
except:
pass
# Create application
app = TaskManagerApp(root)
# Center window
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f'{width}x{height}+{x}+{y}')
root.mainloop()
if __name__ == "__main__":
main()
Features
✅ Core Functionality
- Add/Edit/Delete Tasks - Full CRUD operations for task management
- Task Prioritization - High, Medium, Low priority levels with color coding
- Categories - Organize tasks into customizable categories
- Due Dates - Set and track due dates with overdue indicators
- Completion Tracking - Mark tasks as complete with visual feedback
📊 Dashboard Features
- Real-time Statistics - Total, completed, pending, overdue, and high-priority counts
- Search - Find tasks by title or description
- Filters - Filter by priority, category, and status
- Visual Indicators - Color-coded priorities and overdue warnings
🎨 User Interface
- Modern Design - Clean, professional appearance with sidebar navigation
- Keyboard Shortcuts - Ctrl+N (new), Delete (delete), F5 (refresh)
- Context Menu - Right-click for quick actions
- Double-click Editing - Quick access to edit tasks
Screenshots Preview
┌─────────────────────────────────────────────────────────────────┐
│ 📋 Task Manager Pro _ □ × │
├──────────────┬──────────────────────────────────────────────────┤
│ │ My Tasks │
│ 📋 Task │ 🔍 [Search tasks...] Priority: [All ▼] │
│ Manager │ Category: [All ▼] Status: [All ▼] │
│ ├──────────────────────────────────────────────────┤
│ 📊 Statistics│ ✓ │ Task │ Priority │ Due Date │
│ ├─────┼───────────────────┼──────────┼────────────┤
│ Total Tasks │ ⬜ │ Complete project │ 🔴 High │ 2024-01-15 │
│ 12 │ ✅ │ Review code │ 🟡 Medium│ 2024-01-10 │
│ │ ⬜ │ Write docs │ 🟢 Low │ No date │
│ Completed │ │
│ 5 │ │
│ │ │
│ Pending │ │
│ 7 │ │
│ │ │
│ ⚡ Actions │ [✏️ Edit] [🗑️ Delete] [✓ Toggle Complete] │
│ [+ Add Task] │ │
│ [🔄 Refresh] │ │
└──────────────┴──────────────────────────────────────────────────┘
Database Schema
The application uses SQLite with two tables:
-- Tasks table
CREATE TABLE tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
priority TEXT DEFAULT 'Medium',
category TEXT DEFAULT 'General',
due_date TEXT,
created_date TEXT NOT NULL,
completed INTEGER DEFAULT 0,
completed_date TEXT
);
-- Categories table
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
color TEXT DEFAULT '#3498db'
);
Run the application and start managing your tasks efficiently! 🚀