Personal To-Do List Application using Python

Personal To-Do List Application using Python 


Hi Programmers, 👋

In this tutorial, we will create a Personal To-Do List Application using Python. This project is both simple and enjoyable to build. I will explain the creation process of the project step by step, so make sure to pay close attention to fully understand the tutorial. Let's begin.

Output:



Step-1: Importing Modules:

import tkinter as tk
from tkinter import messagebox, simpledialog
import json

We are utilizing the tkinter module for the GUI aspect of our project. The messagebox function will alert us to the occurrence of an event by displaying a pop-up message. The simpledialog module will allow us to prompt the user for input in a dialog box. Additionally, the json module will help us save and load tasks.

Step-2: Creating the Root App Object:

root = tk.Tk()
root.title("Personal To-Do List")

We are creating a root app object which will act as the GUI.

Step-3: Defining the Functions

Add Task Function:

def add_task():
    task = task_entry.get()
    if task:
        tasks.append({"task": task, "completed": False})
        save_tasks()
        messagebox.showinfo("Success", "Task added successfully")
        task_entry.delete(0, tk.END)
    else:
        messagebox.showerror("Error", "Task field is required")

We will define a function named add_task. We will retrieve the user input with the .get() method from our entry. If the input is valid, we will add the task to the list and save it. If not, an error message will be displayed.

View Tasks Function:

def view_tasks():
    task_list = ""
    for idx, task in enumerate(tasks):
        status = "Completed" if task["completed"] else "Not Completed"
        task_list += f"{idx + 1}. {task['task']} - {status}\n"
    messagebox.showinfo("Tasks", task_list)

We will define a function named view_tasks to display all tasks with their statuses.

Logic:

  1. Initialize task_list String: Start with an empty string to accumulate task details.
  2. Loop Through Tasks: Iterate over the tasks list with an index (enumerate provides both the index and the task).
  3. Determine Status: Check if the task is completed and set the status string accordingly.
  4. Accumulate Task Details: Append each task's details (index, task name, and status) to the task_list string.
  5. Display Tasks: Show the accumulated task_list string in a messagebox.

Mark Task as Completed Function:

def mark_task_completed():
    task_number = simpledialog.askinteger(
        "Input", "Enter task number to mark as completed")
    if task_number and 1 <= task_number <= len(tasks):
        tasks[task_number - 1]["completed"] = True
        save_tasks()
        messagebox.showinfo("Success", "Task marked as completed")
    else:
        messagebox.showerror("Error", "Invalid task number")

We will define a function named mark_task_completed to mark a selected task as completed.

Logic:

  1. Ask for Task Number: Prompt the user to enter the task number to mark as completed.
  2. Validate Input: Check if the entered task number is within the valid range of task indices.
  3. Mark Task: Set the completed status of the specified task to True.
  4. Save Tasks: Call save_tasks() to save the updated task list to the JSON file.
  5. Show Success Message: Inform the user that the task has been successfully marked as completed.
  6. Error Handling: Display an error message if the entered task number is invalid.

Delete Task Function:

def delete_task():
    task_number = simpledialog.askinteger(
        "Input", "Enter task number to delete")
    if task_number and 1 <= task_number <= len(tasks):
        tasks.pop(task_number - 1)
        save_tasks()
        messagebox.showinfo("Success", "Task deleted")
    else:
        messagebox.showerror("Error", "Invalid task number")

We will define a function named delete_task to delete a selected task.

Logic:

  1. Ask for Task Number: Prompt the user to enter the task number to delete.
  2. Validate Input: Check if the entered task number is within the valid range of task indices.
  3. Delete Task: Remove the specified task from the tasks list using pop().
  4. Save Tasks: Call save_tasks() to save the updated task list to the JSON file.
  5. Show Success Message: Inform the user that the task has been successfully deleted.
  6. Error Handling: Display an error message if the entered task number is invalid.


Step-5: Saving and Loading Tasks:

Save Tasks Function:

def save_tasks():
    with open('tasks.json', 'w') as file:
        json.dump(tasks, file)

We will define a function named save_tasks to save the tasks to a JSON file.

Load Tasks Function:

def load_tasks():
    try:
        with open('tasks.json', 'r') as file:
            return json.load(file)
    except FileNotFoundError:
        return []

We will define a function named load_tasks to load the tasks from the JSON file. If the file does not exist, it returns an empty list.

Step-5: Adding Labels, Entries, and Buttons:

tk.Label(root, text="Task").grid(row=0, column=0)

task_entry = tk.Entry(root)
task_entry.grid(row=0, column=1)

tk.Button(root, text="Add Task", command=add_task).grid(
    row=1, column=0, columnspan=2)
tk.Button(root, text="View Tasks", command=view_tasks).grid(
    row=2, column=0, columnspan=2)
tk.Button(root, text="Mark Task as Completed",
          command=mark_task_completed).grid(row=3, column=0, columnspan=2)
tk.Button(root, text="Delete Task", command=delete_task).grid(
    row=4, column=0, columnspan=2)

At this stage, we construct a Label and Entry for the task. The .grid method is used to organize each Label and Entry in a row-wise fashion. Additionally, we introduce buttons linked to the respective commands for adding, viewing, marking, and deleting tasks.

Step-6: Initialize the Task List:

tasks = load_tasks()

Step-7: Execute the App Object:

root.mainloop()

Finally, we will execute the app object in a loop to generate the output.

We have developed a Personal To-Do List Application in Python. You can now enhance this code by adjusting the parameters of the labels and entry fields to improve the application's visual appeal. Fully engage with and comprehend the code, so you can devise innovative solutions for a range of problems using Python.

Happy Learning.🙂