Okay, this is going to be a significant step up! This version incorporates SQLite for data persistence, the "Stop & Start New" button logic, a ttk.Treeview for the daily summary, and improved UI/UX.
Save this as hourly_logger.py:
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from datetime import datetime, timedelta
import pandas as pd
import os
import sqlite3
# --- Constants for Combobox options (German) ---
PLACE_OPTIONS = [
"Büro",
"Homeoffice",
"Kundenstandort", # Example: "Kundenstandort Berlin" - Specifics can go in "Details"
"Unterwegs",
"Sonstiges"
]
ACTIVITY_OVERVIEW_OPTIONS = [
"Projektarbeit", "Entwicklung", "Dokumentation", "Forschung & Analyse", "Testing/QA", "Code-Review",
"Support", "Kundenservice",
"Besprechung", "Meeting", "Team-Update", "Koordination", "Abstimmung", "Präsentation",
"E-Mail-Kommunikation", "Video-Konferenz", "Telefonat",
"Pause", "Mittagspause", "Sport / Bewegung", "Meditation / Entspannung",
"Software-Installation", "Systemwartung", "Datenbank-Management", "Sicherheitsprüfung",
"Verwaltung", "Berichte schreiben", "Zeiterfassung", "Planung & Organisation",
"Schulung / Weiterbildung", "Recherche",
"Sonstiges" # Catch-all for anything not covered
]
# --- Main Application Class ---
class HourlyLogger:
def __init__(self, root):
self.root = root
self.root.title("Zeiterfassung (Hourly Protocol)")
self.root.geometry("800x600") # Set a default window size
self.root.option_add('*tearOff', False) # For menu bar
self.db_path = "hourly_log.db" # SQLite database file
self._init_db() # Initialize SQLite database
self.current_entry = None # Stores the currently running activity's data
self._create_widgets() # Build the UI
self._load_current_activity_state() # Load if previous activity was running on last close
self._load_todays_log() # Populate the daily log table
# Set up cleanup on window close
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
# --- Database Operations ---
def _init_db(self):
"""Initializes the SQLite database and creates the 'activities' table if it doesn't exist."""
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS activities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
place TEXT,
activity_overview TEXT,
start_time TEXT NOT NULL,
end_time TEXT,
duration REAL,
activity_details TEXT
)
""")
conn.commit()
except sqlite3.Error as e:
messagebox.showerror("Database Error", f"Failed to initialize database: {e}")
finally:
if conn:
conn.close()
def _insert_activity(self, data):
"""Inserts a new activity record into the database."""
conn = None
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO activities (date, place, activity_overview, start_time, end_time, duration, activity_details)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (data["Date"], data["Place"], data["Activity (Overview)"],
data["Start Time"], data["End Time"], data["Duration"], data["Activity (Details)"]))
data["id"] = cursor.lastrowid # Get the ID of the newly inserted row
conn.commit()
return True
except sqlite3.Error as e:
messagebox.showerror("Database Error", f"Failed to insert activity: {e}")
return False
finally:
if conn:
conn.close()
def _update_activity(self, activity_id, end_time, duration):
"""Updates an existing activity record in the database."""
conn = None
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
UPDATE activities SET end_time = ?, duration = ? WHERE id = ?
""", (end_time, duration, activity_id))
conn.commit()
return True
except sqlite3.Error as e:
messagebox.showerror("Database Error", f"Failed to update activity: {e}")
return False
finally:
if conn:
conn.close()
def _fetch_activities(self, date_filter=None, unfinished_only=False):
"""Fetches activity records from the database."""
conn = None
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
query = "SELECT id, date, place, activity_overview, start_time, end_time, duration, activity_details FROM activities"
params = []
conditions = []
if date_filter:
conditions.append("date = ?")
params.append(date_filter)
if unfinished_only:
conditions.append("end_time = '' OR end_time IS NULL") # Ensure it's not null either
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY date, start_time DESC" # Latest unfinished first, otherwise chronological
cursor.execute(query, tuple(params))
return cursor.fetchall()
except sqlite3.Error as e:
messagebox.showerror("Database Error", f"Failed to fetch activities: {e}")
return []
finally:
if conn:
conn.close()
# --- UI Creation ---
def _create_widgets(self):
"""Creates and lays out all the GUI elements."""
# Configure grid weights for main window resizing
self.root.grid_rowconfigure(2, weight=1) # Row for the Treeview
self.root.grid_columnconfigure(0, weight=1)
# 1. Input Frame
input_frame = ttk.LabelFrame(self.root, text="Aktuelle Aktivität festlegen")
input_frame.grid(row=0, column=0, padx=10, pady=10, sticky="ew")
input_frame.grid_columnconfigure(1, weight=1) # Allow input fields to expand
# Place
tk.Label(input_frame, text="Ort:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.place_cb = ttk.Combobox(input_frame, values=PLACE_OPTIONS, state="readonly")
self.place_cb.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
self.place_cb.set(PLACE_OPTIONS[0]) # Set default value
# Activity Overview
tk.Label(input_frame, text="Aktivität (Übersicht):").grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.activity_overview_cb = ttk.Combobox(input_frame, values=ACTIVITY_OVERVIEW_OPTIONS, state="readonly")
self.activity_overview_cb.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
self.activity_overview_cb.set(ACTIVITY_OVERVIEW_OPTIONS[0]) # Set default value
# Details
tk.Label(input_frame, text="Details (spezifisch):").grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.details_entry = tk.Entry(input_frame)
self.details_entry.grid(row=2, column=1, padx=5, pady=5, sticky="ew")
# 2. Control Buttons Frame
button_frame = ttk.Frame(self.root)
button_frame.grid(row=1, column=0, padx=10, pady=5, sticky="ew")
button_frame.grid_columnconfigure((0, 1), weight=1) # Make buttons expand equally
self.start_switch_button = tk.Button(button_frame, text="Aktivität starten / wechseln", command=self._start_new_activity)
self.start_switch_button.grid(row=0, column=0, padx=5, pady=5, sticky="ew")
self.end_day_button = tk.Button(button_frame, text="Tag beenden (aktuelle Aktivität stoppen)", command=self._end_day_activity, state=tk.DISABLED)
self.end_day_button.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
# Current Activity Display Label
self.current_activity_label = tk.Label(self.root, text="Aktuell: Keine Aktivität läuft.", fg="blue", font=("Arial", 10, "bold"))
self.current_activity_label.grid(row=2, column=0, padx=10, pady=5, sticky="w")
# 3. Daily Log Table (Treeview)
summary_frame = ttk.LabelFrame(self.root, text="Heutiges Protokoll")
summary_frame.grid(row=3, column=0, padx=10, pady=10, sticky="nsew")
summary_frame.grid_rowconfigure(0, weight=1)
summary_frame.grid_columnconfigure(0, weight=1)
columns = ("Date", "Place", "Overview", "Start", "End", "Duration (h)", "Details")
self.tree = ttk.Treeview(summary_frame, columns=columns, show="headings")
# Define column headings and widths
self.tree.heading("Date", text="Datum")
self.tree.column("Date", width=90, anchor="w")
self.tree.heading("Place", text="Ort")
self.tree.column("Place", width=70, anchor="w")
self.tree.heading("Overview", text="Übersicht")
self.tree.column("Overview", width=120, anchor="w")
self.tree.heading("Start", text="Startzeit")
self.tree.column("Start", width=70, anchor="center")
self.tree.heading("End", text="Endzeit")
self.tree.column("End", width=70, anchor="center")
self.tree.heading("Duration (h)", text="Dauer (h)")
self.tree.column("Duration (h)", width=70, anchor="e") # 'e' for East (right) alignment
self.tree.heading("Details", text="Details")
self.tree.column("Details", width=250, anchor="w")
# Add scrollbars
vsb = ttk.Scrollbar(summary_frame, orient="vertical", command=self.tree.yview)
hsb = ttk.Scrollbar(summary_frame, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
self.tree.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
# 4. Menu Bar
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
file_menu = tk.Menu(menubar)
menubar.add_cascade(label="Datei", menu=file_menu)
file_menu.add_command(label="Nach Excel exportieren...", command=self.export_to_excel)
file_menu.add_separator()
file_menu.add_command(label="Beenden", command=self._on_close)
help_menu = tk.Menu(menubar)
menubar.add_cascade(label="Hilfe", menu=help_menu)
help_menu.add_command(label="Über", command=self._show_about)
# --- Activity Logic ---
def _load_current_activity_state(self):
"""
Checks the database for an unfinished activity (no end_time)
and sets it as the current_entry if found.
This handles app restarts.
"""
# Fetch the latest unfinished activity, if any
unfinished_activities = self._fetch_activities(unfinished_only=True)
if unfinished_activities:
# Get the first (latest) unfinished activity
row = unfinished_activities[0]
self.current_entry = {
"id": row[0],
"Date": row[1],
"Place": row[2],
"Activity (Overview)": row[3],
"Start Time": row[4],
"End Time": row[5], # Will be empty string from DB
"Duration": row[6], # Will be 0.0 from DB
"Activity (Details)": row[7]
}
# Update UI to reflect ongoing activity
self.current_activity_label.config(text=f"Aktuell: {self.current_entry['Activity (Overview)']} - {self.current_entry['Activity (Details)']} (seit {self.current_entry['Start Time']})")
self.start_switch_button.config(text="Aktivität wechseln")
self.end_day_button.config(state=tk.NORMAL)
else:
self.current_entry = None
self.current_activity_label.config(text="Aktuell: Keine Aktivität läuft.")
self.start_switch_button.config(text="Aktivität starten")
self.end_day_button.config(state=tk.DISABLED)
def _load_todays_log(self):
"""Loads and displays today's activities in the Treeview."""
# Clear existing entries in treeview
for item in self.tree.get_children():
self.tree.delete(item)
today_date = datetime.now().strftime("%Y-%m-%d")
rows = self._fetch_activities(date_filter=today_date, unfinished_only=False)
# Insert rows from newest to oldest for easier viewing of current day
for row in reversed(rows): # Reverse to show newest at top (optional)
# Treeview expects values in the order of columns: Date, Place, Overview, Start, End, Duration, Details
self.tree.insert("", "end", values=(row[1], row[2], row[3], row[4], row[5], row[6], row[7]))
def _start_new_activity(self):
"""
Handles stopping the previous activity and starting a new one.
This is the main logging button.
"""
# 1. Input Validation
selected_place = self.place_cb.get()
selected_overview = self.activity_overview_cb.get()
details_text = self.details_entry.get().strip()
if not selected_place or not selected_overview:
messagebox.showwarning("Fehler bei der Eingabe", "Bitte 'Ort' und 'Aktivität (Übersicht)' auswählen.")
return
current_time = datetime.now()
# 2. Stop the currently running activity (if any)
if self.current_entry:
# Calculate duration for the activity that just ended
start_dt = datetime.strptime(self.current_entry["Start Time"], "%H:%M")
end_dt = current_time # This is the current time
duration_td = end_dt - start_dt
duration_hours = round(duration_td.total_seconds() / 3600, 2)
if not self._update_activity(self.current_entry["id"], end_dt.strftime("%H:%M"), duration_hours):
return # Stop if DB update failed
# 3. Start the new activity
new_entry_data = {
"Date": current_time.strftime("%Y-%m-%d"),
"Place": selected_place,
"Activity (Overview)": selected_overview,
"Start Time": current_time.strftime("%H:%M"),
"End Time": "", # Left empty until next activity or day end
"Duration": 0.0, # Will be calculated later
"Activity (Details)": details_text if details_text else "Keine Details angegeben"
}
if not self._insert_activity(new_entry_data):
return # Stop if DB insert failed
self.current_entry = new_entry_data # Update current running activity
self.current_activity_label.config(text=f"Aktuell: {self.current_entry['Activity (Overview)']} - {self.current_entry['Activity (Details)']} (seit {self.current_entry['Start Time']})")
self.start_switch_button.config(text="Aktivität wechseln")
self.end_day_button.config(state=tk.NORMAL)
self.details_entry.delete(0, tk.END) # Clear details field for next input
self._load_todays_log() # Refresh the daily log display
def _end_day_activity(self):
"""Stops the current activity and disables further logging for the day."""
if not self.current_entry:
messagebox.showinfo("Keine Aktivität", "Es läuft keine Aktivität, die beendet werden könnte.")
return
confirm = messagebox.askyesno("Tag beenden", "Möchten Sie die aktuelle Aktivität beenden und die Zeiterfassung für den Tag abschließen?")
if confirm:
current_time = datetime.now()
start_dt = datetime.strptime(self.current_entry["Start Time"], "%H:%M")
duration_td = current_time - start_dt
duration_hours = round(duration_td.total_seconds() / 3600, 2)
if self._update_activity(self.current_entry["id"], current_time.strftime("%H:%M"), duration_hours):
self.current_entry = None # Clear current activity
self.current_activity_label.config(text="Aktuell: Keine Aktivität läuft. Tag beendet.")
self.start_switch_button.config(text="Aktivität starten") # Reset button
self.end_day_button.config(state=tk.DISABLED) # Disable end day button
self._load_todays_log() # Refresh log
messagebox.showinfo("Tag beendet", "Aktuelle Aktivität beendet. Zeiterfassung für den Tag abgeschlossen.")
else:
messagebox.showerror("Fehler", "Fehler beim Beenden der Aktivität.")
# --- Export Functionality ---
def export_to_excel(self):
"""Exports all recorded data from the database to an Excel file."""
conn = None
try:
conn = sqlite3.connect(self.db_path)
# Select all columns in the desired order
df = pd.read_sql_query("SELECT Date, Place, `Activity (Overview)`, Duration, `Start Time`, `End Time`, `Activity (Details)` FROM activities ORDER BY date, start_time", conn)
except sqlite3.Error as e:
messagebox.showerror("Database Error", f"Fehler beim Laden der Daten für den Export: {e}")
return
finally:
if conn:
conn.close()
if df.empty:
messagebox.showwarning("Keine Daten", "Es sind keine Einträge zum Exportieren vorhanden.")
return
# Prompt user for save location
initial_filename = f"Zeiterfassung_{datetime.now().strftime('%Y-%m-%d')}.xlsx"
output_file = filedialog.asksaveasfilename(
defaultextension=".xlsx",
filetypes=[("Excel-Dateien", "*.xlsx"), ("Alle Dateien", "*.*")],
initialfile=initial_filename
)
if not output_file: # User cancelled the save dialog
return
try:
df.to_excel(output_file, index=False)
messagebox.showinfo("Export erfolgreich", f"Daten wurden erfolgreich nach {output_file} exportiert.")
except Exception as e:
messagebox.showerror("Exportfehler", f"Fehler beim Speichern der Excel-Datei: {e}")
# --- Utility and Cleanup ---
def _on_close(self):
"""Handles closing the application window."""
if self.current_entry:
if messagebox.askyesno("Beenden bestätigen", "Es läuft noch eine Aktivität. Soll diese vor dem Beenden gestoppt werden?"):
# Stop the current activity without starting a new one
current_time = datetime.now()
start_dt = datetime.strptime(self.current_entry["Start Time"], "%H:%M")
duration_td = current_time - start_dt
duration_hours = round(duration_td.total_seconds() / 3600, 2)
self._update_activity(self.current_entry["id"], current_time.strftime("%H:%M"), duration_hours)
self._load_todays_log() # Update the log once more
if messagebox.askyesno("Beenden bestätigen", "Möchten Sie alle Daten vor dem Beenden nach Excel exportieren?"):
self.export_to_excel()
self.root.destroy()
def _show_about(self):
messagebox.showinfo("Über Zeiterfassung", "Zeiterfassung (Hourly Protocol)\n\nEine einfache App zur Protokollierung Ihrer täglichen Aktivitäten.\n\nEntwickelt mit Python und Tkinter.")
# --- Run the Application ---
if __name__ == "__main__":
root = tk.Tk()
app = HourlyLogger(root)
root.mainloop()