Here’s the final polished version of your hourly_logger.py script, incorporating all improvements for robustness, usability, and professional output:
✅ Final Features:
- German activity categories with separators.
- Input validation to prevent invalid entries.
- Real-time clock and padded UI layout.
- Excel export with user-defined save paths and formatted columns.
- Unsaved activity warnings on app close.
- Clean code structure with constants and error handling.
📄 Full Code (hourly_logger.py)
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from datetime import datetime
import pandas as pd
import os
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
# --- Constants ---
ACTIVITY_CATEGORIES = [
# Work Types
"Projektarbeit", "Entwicklung", "Dokumentation", "Forschung & Analyse",
"Testing/QA", "Code-Review", "Support", "Kundenservice",
"--------------------",
# Meetings & Communication
"Besprechung", "Meeting", "Team-Update", "Koordination", "Abstimmung",
"Präsentation", "E-Mail-Kommunikation", "Video-Konferenz",
"--------------------",
# Personal / Wellness
"Pause", "Mittagspause", "Sport / Bewegung", "Meditation / Entspannung",
"--------------------",
# Technical Tasks
"Software-Installation", "Systemwartung", "Datenbank-Management", "Sicherheitsprüfung",
"--------------------",
# Administrative Tasks
"Verwaltung", "Berichte schreiben", "Zeiterfassung", "Planung & Organisation",
"--------------------",
# General / Other
"Schulung / Weiterbildung", "Recherche", "Telefonat", "Sonstiges"
]
PLACES = ["Büro", "Homeoffice", "Unterwegs", "Kunde vor Ort", "Sonstiges"]
class HourlyLogger:
def __init__(self, root):
self.root = root
self.root.title("Protokolllogger")
self.entries = []
self.current_entry = {}
# --- UI Elements ---
# Activity Overview
tk.Label(root, text="Tätigkeit:").grid(row=0, column=0)
self.activity_overview = ttk.Combobox(root, values=ACTIVITY_CATEGORIES, width=30)
self.activity_overview.grid(row=0, column=1)
# Place
tk.Label(root, text="Ort:").grid(row=1, column=0)
self.place = ttk.Combobox(root, values=PLACES, width=30)
self.place.grid(row=1, column=1)
# Details
tk.Label(root, text="Details:").grid(row=2, column=0)
self.details = tk.Entry(root, width=30)
self.details.grid(row=2, column=1)
# Buttons
self.start_button = tk.Button(root, text="Start", command=self.start_activity)
self.start_button.grid(row=3, column=0, columnspan=2, pady=5)
self.stop_button = tk.Button(root, text="Stop", command=self.stop_activity, state=tk.DISABLED)
self.stop_button.grid(row=4, column=0, columnspan=2, pady=5)
# Summary Log
self.summary = tk.Text(root, height=10, width=60)
self.summary.grid(row=5, column=0, columnspan=3, padx=5, pady=5)
# Real-time Clock
self.time_label = tk.Label(root, text="", fg="gray")
self.time_label.grid(row=0, column=2, padx=10)
self.update_clock()
# Apply padding to all widgets
for child in root.winfo_children():
child.grid_configure(padx=5, pady=2)
# --- Core Functions ---
def start_activity(self):
activity = self.activity_overview.get()
place = self.place.get()
if activity == "--------------------" or not activity or not place:
messagebox.showwarning("Ungültige Eingabe", "Bitte wählen Sie eine gültige Tätigkeit und einen Ort.")
return
self.current_entry = {
"Datum": datetime.now().strftime("%Y-%m-%d"),
"Ort": place,
"Tätigkeit (Übersicht)": activity,
"Startzeit": datetime.now().strftime("%H:%M"),
"Endzeit": "",
"Tätigkeit (Details)": self.details.get()
}
self.stop_button.config(state=tk.NORMAL)
self.start_button.config(state=tk.DISABLED)
self.summary.insert(tk.END, f"Gestartet: {activity} um {self.current_entry['Startzeit']}\n")
def stop_activity(self):
if not self.current_entry:
return
self.current_entry["Endzeit"] = datetime.now().strftime("%H:%M")
self.entries.append(self.current_entry.copy())
self.stop_button.config(state=tk.DISABLED)
self.start_button.config(state=tk.NORMAL)
self.details.delete(0, tk.END)
duration = self.calculate_duration(self.current_entry["Startzeit"], self.current_entry["Endzeit"])
self.summary.insert(tk.END, f"Beendet: Dauer: {duration} Stunden\n\n")
def calculate_duration(self, start, end):
start_time = datetime.strptime(start, "%H:%M")
end_time = datetime.strptime(end, "%H:%M")
duration = (end_time - start_time).seconds / 3600
return round(duration, 2)
def export_to_excel(self):
if not self.entries:
messagebox.showwarning("Keine Daten", "Es gibt keine Einträge zum Exportieren.")
return
file_path = filedialog.asksaveasfilename(
defaultextension=".xlsx",
filetypes=[("Excel-Datei", "*.xlsx")],
title="Speichern unter"
)
if not file_path:
return # Abgebrochen
try:
df = pd.DataFrame(self.entries)
df["Dauer"] = df.apply(lambda row: self.calculate_duration(row["Startzeit"], row["Endzeit"]), axis=1)
df = df[["Datum", "Ort", "Tätigkeit (Übersicht)", "Dauer", "Startzeit", "Endzeit", "Tätigkeit (Details)"]]
df.to_excel(file_path, index=False)
# Autofit columns
wb = load_workbook(file_path)
ws = wb.active
for col in ws.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
ws.column_dimensions[column].width = min(max_length + 2, 50)
wb.save(file_path)
messagebox.showinfo("Erfolg", f"Protokoll gespeichert:\n{file_path}")
except Exception as e:
messagebox.showerror("Fehler", f"Speichern fehlgeschlagen:\n{str(e)}")
# --- Helper Functions ---
def update_clock(self):
self.time_label.config(text=datetime.now().strftime("%H:%M:%S"))
self.root.after(1000, self.update_clock)
# --- App Lifecycle ---
def on_close():
if logger.current_entry and logger.current_entry.get("Startzeit") and not logger.current_entry.get("Endzeit"):
if not messagebox.askyesno("Unsaved Activity", "Eine Tätigkeit läuft noch. Schließen?"):
return
if messagebox.askyesno("Beenden", "Daten exportieren vor dem Schließen?"):
logger.export_to_excel()
root.destroy()
# --- Run App ---
if __name__ == "__main__":
root = tk.Tk()
logger = HourlyLogger(root)
root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()