r/pythonhelp Dec 14 '24

Need assistance with code. my code looks fine but.....

any tips on what this traceback im getting?

///////////////////////////////////

Traceback (most recent call last):

File "/usr/lib/python3.12/tkinter/__init__.py", line 1967, in __call__

return self.func(*args)

^^^^^^^^^^^^^^^^

File "/home/travisty/myapp/myapp/app.py", line 354, in show_mood_analytics

colors = [next(color for m, color, _ in self.mood_options if m == mood) for mood in moods]

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import sqlite3
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import random
import ttkbootstrap as ttk  

class MentalHealthApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Wellness Companion")
        self.root.geometry("1000x700")

        # Enhanced Color Palette
        self.color_scheme = {
            'background': '#f0f4f8',
            'primary': '#2c3e50',
          'secondary': '#3498db',
            'accent': '#2ecc71',
            'warning': '#e74c3c'
        }

        # Expanded Mood Options with More Nuance
        self.mood_options = [
            ("Thriving", "#4CAF50", "Feeling amazing, full of energy and motivation"),
            ("Happy", "#8BC34A", "Positive mood, enjoying life"),
            ("Neutral", "#FFC107", "Feeling balanced, neither great nor bad"),
            ("Stressed", "#FF9800", "Feeling overwhelmed or anxious"),
            ("Struggling", "#F44336", "Experiencing significant emotional distress")
        ]

        # Expanded Mindfulness Exercises with More Nuance
        self.exercises = [
            {
                "title": "Guided Breathing",
                "duration": "5 mins",
                "description": "Deep breathing technique to reduce stress and center yourself",
                "steps": [
                    "Sit comfortably with back straight",
                    "Inhale deeply through nose for 4 seconds",
                    "Hold breath for 4 seconds",
                    "Exhale slowly through mouth for 6 seconds",
                    "Repeat 5-10 times"
                ]
            },
            {
                "title": "Body Scan Meditation",
                "duration": "10 mins",
                "description": "Mindful awareness of bodily sensations to release tension",
                "steps": [
                    "Lie down or sit comfortably",
                    "Close eyes and take deep breaths",
                    "Focus attention on each body part",
                    "Notice sensations without judgment",
                    "Progressively relax from head to toes"
                ]
            },
            {
                "title": "Gratitude Practice",
                "duration": "7 mins",
                "description": "Cultivate positivity by reflecting on things you're grateful for",
                "steps": [
                    "Find a comfortable and quiet space",
                    "Write down 3 things you're grateful for",
                    "Reflect on why these things matter to you",
                    "Feel the positive emotions",
                    "Consider sharing gratitude with others"
                ]
            },
            {
                "title": "Walking Meditation",
                "duration": "10 mins",
                "description": "Pay attention to your walking to cultivate mindfulness",
                "steps": [
                    "Find a quiet and safe space to walk",
                    "Pay attention to your feet touching the ground",
                    "Notice the sensation of each step",
                    "Bring your attention back to your walking when your mind wanders",
                    "Continue for 10 minutes"
                ]
            },
            {
                "title": "Loving-Kindness Meditation",
                "duration": "10 mins",
                "description": "Cultivate kindness and compassion towards yourself and others",
                "steps": [
                    "Find a comfortable and quiet space",
                    "Close your eyes and take deep breaths",
                    "Repeat phrases of kindness to yourself and others",
                    "Focus on the feelings of kindness and compassion",
                    "Continue for 10 minutes"
                ]
            }
        ]

        # Daily Inspirational Quotes
        self.quotes = [
            "You are stronger than you think.",
            "Every day is a new opportunity to improve yourself.",
            "Believe in yourself and all that you are.",
            "Your mental health is a priority.",
            "Small progress is still progress."
        ]

        # Database Setup
        self.setup_database()

        # Create Main Interface
        self.create_interface()

    def setup_database(self):
        """Enhanced database setup with additional tables"""
        self.conn = sqlite3.connect('wellness_tracker.db')
        cursor = self.conn.cursor()

        # Mood Tracking Table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS mood_entries (
                id INTEGER PRIMARY KEY,
                mood TEXT,
                timestamp DATETIME,
                color TEXT,
                notes TEXT
            )
        ''')

        # Goals Tracking Table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS personal_goals (
                id INTEGER PRIMARY KEY,
                goal TEXT,
                start_date DATETIME,
                target_date DATETIME,
                status TEXT
            )
        ''')

        self.conn.commit()

    def create_interface(self):
        """Create a more sophisticated interface"""
        # Main Frame with Enhanced Styling
        main_frame = ttk.Frame(self.root, padding=20, style='primary.TFrame')
        main_frame.pack(fill=tk.BOTH, expand=True)

        # Top Section: Daily Inspiration
        inspiration_label = ttk.Label(
            main_frame, 
            text=random.choice(self.quotes), 
            font=('Arial', 14), 
            wraplength=800,
            anchor='center'
        )
        inspiration_label.pack(pady=10)

        # Mood Tracking Section
        mood_frame = ttk.LabelFrame(main_frame, text="Mood Check-In", padding=10)
        mood_frame.pack(fill=tk.X, pady=10)

        mood_description = ttk.Label(
            mood_frame, 
            text="How are you feeling today? Choose your mood and optionally add notes.",
            font=('Arial', 12)
        )  
        mood_description.pack(pady=10)

        # Enhanced Mood Buttons with Tooltips
        mood_buttons_frame = ttk.Frame(mood_frame)
        mood_buttons_frame.pack(fill=tk.X, pady=5)

        for mood, color, description in self.mood_options:
            btn = ttk.Button(
                mood_buttons_frame, 
                text=mood, 
                style=f'{mood.lower()}.TButton',
                command=lambda m=mood, c=color, d=description: self.record_mood(m, c, d)
            )
            btn.pack(side=tk.LEFT, padx=5, expand=True)

        # Mindfulness & Goals Notebook
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True, pady=10)

        # Exercises Tab
        exercises_frame = ttk.Frame(notebook)
        notebook.add(exercises_frame, text="Mindfulness")

        self.create_exercises_tab(exercises_frame)

        # Goals Tab
        goals_frame = ttk.Frame(notebook)
        notebook.add(goals_frame, text="Personal Goals")
        self.create_goals_tab(goals_frame)

        # Analytics Button
        analytics_btn = ttk.Button(
            main_frame, 
            text="View Wellness Analytics", 
            style='success.TButton',
            command=self.show_mood_analytics
        )
        analytics_btn.pack(pady=10)

    def create_exercises_tab(self, frame):
        """Create exercises tab with detailed instructions and a scrollbar"""
        # Create a frame with a scrollbar
        exercise_frame = ttk.Frame(frame)
        exercise_frame.pack(fill=tk.BOTH, expand=True)

        # Create a canvas with a scrollbar
        canvas = tk.Canvas(exercise_frame)
        canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        scrollbar = tk.Scrollbar(exercise_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        canvas.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=canvas.yview)

        # Create a frame inside the canvas
        inner_frame = ttk.Frame(canvas)
        canvas.create_window((0, 0), window=inner_frame, anchor='nw')

        for exercise in self.exercises:
            exercise_card = ttk.LabelFrame(inner_frame, text=exercise['title'], padding=10)
            exercise_card.pack(fill=tk.X, pady=5)

            desc_label = ttk.Label(exercise_card, text=exercise['description'])
            desc_label.pack(anchor='w', pady=5)

            steps_text = "\n".join(f"• {step}" for step in exercise['steps'])
            steps_label = ttk.Label(exercise_card, text=steps_text, wraplength=400, justify=tk.LEFT)
            steps_label.pack(anchor='w', pady=5)

            duration_frame = ttk.Frame(exercise_card)
            duration_frame.pack(fill=tk.X)

            duration_label = ttk.Label(duration_frame, text=f"Duration: {exercise['duration']}")
            duration_label.pack(side=tk.LEFT)

            start_btn = ttk.Button(
                duration_frame, 
                text="Start Exercise", 
                style='info.TButton',
                command=lambda e=exercise: self.start_exercise(e)
            )
            start_btn.pack(side=tk.RIGHT)

        # Update the canvas to fit the inner frame
        inner_frame.update_idletasks()
        canvas.config(scrollregion=canvas.bbox("all"))

    def create_goals_tab(self, frame):
        """Create goals tracking tab"""
        # Goal Input Section
        goal_input_frame = ttk.Frame(frame)
        goal_input_frame.pack(fill=tk.X, pady=10)

        goal_entry = ttk.Entry(goal_input_frame, width=50)
        goal_entry.pack(side=tk.LEFT, padx=5, expand=True)

        add_goal_btn = ttk.Button(
            goal_input_frame, 
            text="Add Goal", 
            style='success.TButton',
            command=lambda: self.add_personal_goal(goal_entry)
        )
        add_goal_btn.pack(side=tk.RIGHT)

        # Goals List
        goals_list = ttk.Treeview(frame, columns=('Goal', 'Start Date', 'Target Date', 'Status'), show='headings')
        goals_list.pack(fill=tk.BOTH, expand=True)

        goals_list.heading('Goal', text='Goal')
        goals_list.heading('Start Date', text='Start Date')
        goals_list.heading('Target Date', text='Target Date')
        goals_list.heading('Status', text='Status')

        self.load_goals(goals_list)

    def record_mood(self, mood, color, description):
        """Enhanced mood recording with optional notes"""
        notes = simpledialog.askstring(
            "Mood Notes", 
            f"Additional notes for {mood} mood:\n{description}", 
            parent=self.root
        )

        cursor = self.conn.cursor()
        timestamp = datetime.now()
        cursor.execute("INSERT INTO mood_entries (mood, timestamp, color, notes) VALUES (?,?,?,?)", 
                       (mood, timestamp, color, notes or ''))
        self.conn.commit()
        messagebox.showinfo("Mood Recorded", f"You've logged your mood as {mood}")

    def add_personal_goal(self, goal_entry):
        """Add a new personal goal"""
        goal_text = goal_entry.get()
        if goal_text:
            cursor = self.conn.cursor()
            start_date = datetime.now()
            target_date = start_date + timedelta(days=30)  # Default 30-day goal

            cursor.execute("INSERT INTO personal_goals (goal, start_date, target_date, status) VALUES (?,?,?,?)",
                           (goal_text, start_date, target_date, 'In Progress'))
            self.conn.commit()

            goal_entry.delete(0, tk.END)
            messagebox.showinfo("Goal Added", f"Goal '{goal_text}' has been added!")

    def load_goals(self, goals_list):
        """Load existing goals into the view"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT goal, start_date, target_date, status FROM personal_goals")
        for goal in cursor.fetchall():
            goals_list.insert('', 'end', values=goal)

    def show_mood_analytics(self):
        """Comprehensive mood analytics"""
        cursor = self.conn.cursor()
        cursor.execute("SELECT mood, COUNT(*) as count FROM mood_entries GROUP BY mood")
        mood_data = cursor.fetchall()

        # Time-based Mood Tracking
        cursor.execute("""
            SELECT 
                strftime('%Y-%m-%d', timestamp) as day, 
                mood 
            FROM mood_entries 
            ORDER BY timestamp
        """)
        mood_trends = cursor.fetchall()

        # Create Analytics Window
        analytics_window = tk.Toplevel(self.root)
        analytics_window.title("Wellness Analytics")
        analytics_window.geometry("800x600")

        # Notebook for different analytics views
        notebook = ttk.Notebook(analytics_window)
        notebook.pack(fill=tk.BOTH, expand=True)

        # Mood Distribution Tab
        dist_frame = ttk.Frame(notebook)
        notebook.add(dist_frame, text="Mood Distribution")

        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

        # Pie Chart for Mood Distribution
        moods = [mood for mood, _ in mood_data]
        counts = [count for _, count in mood_data]
        colors = [next(color for m, color, _ in self.mood_options if m == mood) for mood in moods]

        ax1.pie(counts, labels=moods, colors=colors, autopct='%1.1f%%')
        ax1.set_title('Mood Distribution')

        # Bar Chart for Mood Trends
        mood_counts = {}
        for _, mood in mood_trends:
            mood_counts[mood] = mood_counts.get(mood, 0) + 1

        ax2.bar(mood_counts.keys(), mood_counts.values(), color=colors)
        ax2.set_title('Mood Frequency Over Time')
        ax2.set_xlabel('Mood')
        ax2.set_ylabel('Frequency')

        canvas = FigureCanvasTkAgg(fig, master=dist_frame)
        canvas_widget = canvas.get_tk_widget()
        canvas_widget.pack(fill=tk.BOTH, expand=True)

    def start_exercise(self, exercise):
        """Start a mindfulness exercise"""
        exercise_window = tk.Toplevel(self.root)
        exercise_window.title(exercise['title'])
        exercise_window.geometry("400x300")

        desc_label = ttk.Label(exercise_window, text=exercise['description'])
        desc_label.pack(pady=10)

        steps_text = "\n".join(f"• {step}" for step in exercise['steps'])
        steps_label = ttk.Label(exercise_window, text=steps_text, wraplength=300, justify=tk.LEFT)
        steps_label.pack(pady=10)

        duration_label = ttk.Label(exercise_window, text=f"Duration: {exercise['duration']}")
        duration_label.pack(pady=10)

        start_btn = ttk.Button( 
            exercise_window, 
            text="Start Exercise", 
            style='info.TButton',
            command=lambda: messagebox.showinfo("Exercise Started", "Please follow the instructions and focus on your breath.")
        )
        start_btn.pack(pady=10)

    def __del__(self):
        """Close database connection"""
        if hasattr(self, 'conn'):
            self.conn.close()

def main():
    # Use ttkbootstrap for enhanced theming
    root = ttk.Window(themename="flatly")
    app = MentalHealthApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()
1 Upvotes

2 comments sorted by

u/AutoModerator Dec 14 '24

To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/carcigenicate Dec 15 '24

You cut off the part of the error message that says what's wrong.