Habit Tracker

 import sqlite3

import tkinter as tk

from tkinter import messagebox


# Database Setup

conn = sqlite3.connect("habits.db")

cursor = conn.cursor()

cursor.execute("""

    CREATE TABLE IF NOT EXISTS habits (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        name TEXT NOT NULL,

        status TEXT DEFAULT 'Pending'

    )

""")

conn.commit()


# Function to add a new habit

def add_habit():

    habit_name = habit_entry.get().strip()

    if habit_name:

        cursor.execute("INSERT INTO habits (name, status) VALUES (?, 'Pending')", (habit_name,))

        conn.commit()

        habit_entry.delete(0, tk.END)

        load_habits()

    else:

        messagebox.showwarning("Warning", "Please enter a habit name!")


# Function to mark a habit as completed

def complete_habit(habit_id):

    cursor.execute("UPDATE habits SET status = 'Completed' WHERE id = ?", (habit_id,))

    conn.commit()

    load_habits()


# Function to delete a habit

def delete_habit(habit_id):

    cursor.execute("DELETE FROM habits WHERE id = ?", (habit_id,))

    conn.commit()

    load_habits()


# Function to load habits from the database

def load_habits():

    habit_list.delete(0, tk.END)

    cursor.execute("SELECT id, name, status FROM habits")

    for habit in cursor.fetchall():

        habit_id, name, status = habit

        habit_list.insert(tk.END, f"{habit_id}. {name} - {status}")


# GUI Setup

root = tk.Tk()

root.title("Habit Tracker")

root.geometry("400x500")


tk.Label(root, text="Enter a New Habit:", font=("Arial", 12)).pack(pady=5)

habit_entry = tk.Entry(root, width=40)

habit_entry.pack(pady=5)

tk.Button(root, text="Add Habit", command=add_habit).pack(pady=5)


tk.Label(root, text="Your Habits:", font=("Arial", 12)).pack(pady=5)

habit_list = tk.Listbox(root, width=50, height=10)

habit_list.pack()


tk.Button(root, text="Mark as Completed", command=lambda: complete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)

tk.Button(root, text="Delete Habit", command=lambda: delete_habit(habit_list.get(tk.ACTIVE).split('.')[0])).pack(pady=5)


load_habits()


root.mainloop()


No comments: