-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeckermitSoundttk.py
More file actions
421 lines (345 loc) · 16.5 KB
/
WeckermitSoundttk.py
File metadata and controls
421 lines (345 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
Wecker mit Sound - Optimierte Version
Ein runder, skalierbarer Wecker mit Tkinter-GUI und Pygame-Sound.
"""
import tkinter as tk
from tkinter import ttk, messagebox
import datetime
import pygame
import pystray
from PIL import Image, ImageDraw
class AlarmClock:
def __init__(self):
self.alarm_time = None
self.alarm_sound_file_set = "beep-09.wav"
self.alarm_sound_file_alarm = "sanfter-wecker.mp3"
self.alarm_sound_set = None
self.alarm_sound_alarm = None
self.tray_icon = None
self.is_minimized = False
self.init_pygame()
self.init_gui()
def init_pygame(self):
"""Initialisiert Pygame und lädt Sounddateien."""
try:
pygame.mixer.init()
self.alarm_sound_set = pygame.mixer.Sound(self.alarm_sound_file_set)
self.alarm_sound_alarm = pygame.mixer.Sound(self.alarm_sound_file_alarm)
except pygame.error as e:
print(f"Sound-Fehler: {e}")
self.alarm_sound_set = None
self.alarm_sound_alarm = None
def init_gui(self):
"""Initialisiert das GUI-Fenster."""
self.root = tk.Tk()
self.root.title("Wecker")
self.root.resizable(False, False)
# Grundlegende Fenster-Einstellungen
self.mask_color = "#123456"
# overrideredirect entfernt für normale Taskleisten-Integration
self.root.config(bg=self.mask_color)
self.size = 350
self.min_size = 80
self.root.geometry(f"{self.size}x{self.size}+200+100")
# Canvas für Kreis-Design
self.circle_color = "#4A90E2"
self.text_color = "#FFFFFF"
# Konfiguriere ttk Styles
self.setup_styles()
self.canvas = tk.Canvas(self.root, width=self.size, height=self.size,
highlightthickness=0, bg=self.mask_color)
self.canvas.pack()
self.oval_id = self.canvas.create_oval(3, 3, self.size-3, self.size-3,
fill=self.circle_color, outline="#2E5C8A", width=2)
# Inner Frame für Widgets
self.inner_frame = ttk.Frame(self.canvas, style='Custom.TFrame')
# Widgets erstellen
self.create_widgets()
# Fenster positionieren und skalieren
self.inner_window = self.canvas.create_window(self.size/2, self.size/2, window=self.inner_frame)
self.minimize_window_id = self.canvas.create_window(self.size-20, self.size-20, window=self.minimize_btn)
# Event-Bindings für Drag und Resize
self.bind_events()
# Schriftgrößen anpassen
self.adjust_widget_fonts(self.size)
def setup_styles(self):
"""Konfiguriert ttk-Styles."""
style = ttk.Style()
# Button Styles
style.configure('Set.TButton',
background='#2ECC71',
foreground='white',
font=('Helvetica', 10, 'bold'),
borderwidth=0)
style.map('Set.TButton',
background=[('active', '#27AE60')])
style.configure('Minimize.TButton',
background="#12D1F3",
foreground='white',
font=('Helvetica', 14, 'bold'),
borderwidth=0)
# Label Styles
style.configure('Time.TLabel',
background=self.circle_color,
foreground="#FEFFFD",
font=('Helvetica', 32, 'bold'))
style.configure('Date.TLabel',
background=self.circle_color,
foreground="#FAF8F8",
font=('Helvetica', 18, 'bold'))
style.configure('TimeText.TLabel',
background=self.circle_color,
foreground=self.text_color,
font=('Helvetica', 10))
style.configure('Status.TLabel',
background=self.circle_color,
foreground='#FFFF00',
font=('Helvetica', 10))
style.configure('Info.TLabel',
background=self.circle_color,
foreground=self.text_color,
font=('Helvetica', 9))
# Entry Style
style.configure('Custom.TEntry',
fieldbackground='white',
font=('Helvetica', 11, 'bold'))
# Frame Style
style.configure('Custom.TFrame',
background=self.circle_color)
def create_widgets(self):
"""Erstellt alle GUI-Widgets."""
# Aktuelles Datum
self.current_date_label = ttk.Label(self.inner_frame, text="--.--.----",
style='Date.TLabel', anchor='center')
self.current_date_label.pack(pady=(20, 0), anchor='center')
# Aktuelle Zeit
self.current_time_label = ttk.Label(self.inner_frame, text="--:--:--",
style='Time.TLabel', anchor='center')
self.current_time_label.pack(pady=(5, 5), anchor='center')
self.time_label = ttk.Label(self.inner_frame, text="Aktuelle Zeit",
style='TimeText.TLabel')
self.time_label.pack()
# Eingabefelder für Zeit
time_frame = ttk.Frame(self.inner_frame, style='Custom.TFrame')
time_frame.pack(pady=12)
ttk.Label(time_frame, text="Stunde (HH):", style='Info.TLabel').pack(side=tk.LEFT, padx=3)
self.hour_entry = ttk.Entry(time_frame, width=3, style='Custom.TEntry')
self.hour_entry.pack(side=tk.LEFT, padx=2)
self.hour_entry.insert(0, "16")
# Mausrad-Binding für Stunden
self.hour_entry.bind("<MouseWheel>", lambda e: self.on_mousewheel_hour(e))
self.hour_entry.bind("<Button-4>", lambda e: self.on_mousewheel_hour(e)) # Linux scroll up
self.hour_entry.bind("<Button-5>", lambda e: self.on_mousewheel_hour(e)) # Linux scroll down
ttk.Label(time_frame, text="Minute (MM):", style='Info.TLabel').pack(side=tk.LEFT, padx=3)
self.minute_entry = ttk.Entry(time_frame, width=3, style='Custom.TEntry')
self.minute_entry.pack(side=tk.LEFT, padx=2)
self.minute_entry.insert(0, "15")
# Mausrad-Binding für Minuten
self.minute_entry.bind("<MouseWheel>", lambda e: self.on_mousewheel_minute(e))
self.minute_entry.bind("<Button-4>", lambda e: self.on_mousewheel_minute(e)) # Linux scroll up
self.minute_entry.bind("<Button-5>", lambda e: self.on_mousewheel_minute(e)) # Linux scroll down
# Button zum Stellen des Weckers
self.set_button = tk.Button(self.inner_frame, text="Wecker stellen",
command=self.set_alarm, bg="#2ECC71", fg="white",
font=('Helvetica', 10, 'bold'), padx=8, pady=5,
relief=tk.RAISED, bd=2, activebackground="#27AE60")
self.set_button.pack(pady=8)
# Status-Label
self.status_label = tk.Label(self.inner_frame, text="Weckzeit eingeben",
fg="#FFFF00", bg=self.circle_color, font=('Helvetica', 10))
self.status_label.pack(pady=8)
# Minimize Button
self.minimize_btn = tk.Button(self.root, text="—", command=self.minimize_window,
bd=0, bg="#F39C12", fg="white", font=('Helvetica', 14, 'bold'),
relief=tk.FLAT, activebackground="#E67E22")
def adjust_widget_fonts(self, size_px):
"""Passt Schriftgrößen proportional zur Fenstergröße an."""
scale = size_px / 350.0
time_font = max(10, int(32 * scale))
small_font = max(6, int(10 * scale))
entry_font = max(6, int(11 * scale))
btn_font = max(6, int(10 * scale))
close_font = max(8, int(14 * scale))
try:
self.current_time_label.config(font=('Helvetica', time_font, 'bold'))
self.time_label.config(font=('Helvetica', small_font))
self.hour_entry.config(font=('Helvetica', entry_font, 'bold'))
self.minute_entry.config(font=('Helvetica', entry_font, 'bold'))
self.set_button.config(font=('Helvetica', btn_font, 'bold'))
self.status_label.config(font=('Helvetica', small_font))
self.minimize_btn.config(font=('Helvetica', close_font, 'bold'))
except Exception:
pass # Widgets noch nicht initialisiert
def on_mousewheel_hour(self, event):
"""Erhöht/verringert Stunden mit dem Mausrad."""
try:
current_value = int(self.hour_entry.get())
except ValueError:
current_value = 0
# Bestimme Scroll-Richtung (Windows/Mac vs Linux)
if event.num == 4 or event.delta > 0: # Scroll up
new_value = (current_value + 1) % 24
elif event.num == 5 or event.delta < 0: # Scroll down
new_value = (current_value - 1) % 24
else:
return
self.hour_entry.delete(0, tk.END)
self.hour_entry.insert(0, str(new_value).zfill(2))
def on_mousewheel_minute(self, event):
"""Erhöht/verringert Minuten mit dem Mausrad."""
try:
current_value = int(self.minute_entry.get())
except ValueError:
current_value = 0
# Bestimme Scroll-Richtung (Windows/Mac vs Linux)
if event.num == 4 or event.delta > 0: # Scroll up
new_value = (current_value + 1) % 60
elif event.num == 5 or event.delta < 0: # Scroll down
new_value = (current_value - 1) % 60
else:
return
self.minute_entry.delete(0, tk.END)
self.minute_entry.insert(0, str(new_value).zfill(2))
def set_alarm(self):
"""Stellt den Wecker auf die eingegebene Zeit."""
hour_str = self.hour_entry.get().zfill(2)
minute_str = self.minute_entry.get().zfill(2)
try:
alarm_hour = int(hour_str)
alarm_minute = int(minute_str)
if not (0 <= alarm_hour <= 23 and 0 <= alarm_minute <= 59):
messagebox.showerror("Fehler", "Ungültige Uhrzeit. Bitte hh (00-23) und mm (00-59) eingeben.")
return
# Stoppe laufenden Alarm
if pygame.mixer.get_busy():
pygame.mixer.stop()
self.alarm_time = f"{hour_str}:{minute_str}"
self.status_label.config(text=f"✓ Wecker gestellt: {self.alarm_time}", fg="#00FF00")
# Sound abspielen beim Stellen
if self.alarm_sound_set:
self.alarm_sound_set.play()
except ValueError:
messagebox.showerror("Fehler", "Ungültige Eingabe. Bitte nur Zahlen verwenden.")
self.alarm_time = None
self.status_label.config(text="Wecker nicht gestellt", fg="#FF6B6B")
def check_alarm(self):
"""Überprüft die aktuelle Zeit und löst Alarm aus, falls nötig."""
now = datetime.datetime.now()
now_str = now.strftime("%H:%M:%S")
date_str = now.strftime("%d.%m.%Y")
self.current_time_label.config(text=now_str)
self.current_date_label.config(text=date_str)
if self.alarm_time:
now_minutes = now.strftime("%H:%M")
if now_minutes == self.alarm_time:
self.trigger_alarm()
# Nächste Überprüfung in 1 Sekunde
self.root.after(1000, self.check_alarm)
def trigger_alarm(self):
"""Löst den Alarm aus."""
self.status_label.config(text="🔔 ALARM!!! WACH AUF!", fg="#FF6B6B")
if self.alarm_sound_alarm:
self.alarm_sound_alarm.play(loops=-1)
messagebox.showinfo("Wecker", "Die eingestellte Zeit ist erreicht! Klicken Sie auf OK, um den Alarm zu stoppen.")
if pygame.mixer.get_busy():
pygame.mixer.stop()
self.alarm_time = None
self.status_label.config(text="Alarm deaktiviert", fg="#FFFFFF")
def minimize_window(self):
"""Minimiert das Fenster in den System-Tray."""
print("Minimizing to tray")
self.is_minimized = True
self.root.withdraw() # Verstecke das Fenster
if not self.tray_icon:
self.show_tray()
def show_tray(self):
"""Zeigt das Tray-Icon an."""
if self.tray_icon is not None:
return # Tray-Icon existiert bereits
print("Showing tray icon")
# Erstelle ein einfaches Icon
image = Image.new('RGB', (64, 64), color=(74, 144, 226))
draw = ImageDraw.Draw(image)
draw.ellipse((16, 16, 48, 48), fill=(255, 255, 255))
# Tray-Menü
menu = pystray.Menu(
pystray.MenuItem("Anzeigen", self.restore_window, default=True),
pystray.MenuItem("Beenden", self.quit_app)
)
self.tray_icon = pystray.Icon("Wecker", image, "Wecker App", menu)
self.tray_icon.run_detached()
def restore_window_callback(self, icon=None, item=None):
"""Callback vom Tray-Icon - plant Wiederherstellung im Hauptthread."""
print("Restore callback triggered")
# Plane die Wiederherstellung im Tkinter Hauptthread
self.root.after(0, self.restore_window)
def restore_window(self):
"""Stellt das Fenster wieder her."""
print("Restoring window")
if not self.is_minimized:
return
self.is_minimized = False
# Stoppe das Tray-Icon
if self.tray_icon:
try:
self.tray_icon.stop()
except Exception as e:
print(f"Fehler beim Stoppen des Tray-Icons: {e}")
finally:
self.tray_icon = None
# Fenster wiederherstellen - optimiert für Geschwindigkeit
try:
self.root.deiconify()
self.root.geometry(f"{self.size}x{self.size}+200+100")
self.root.attributes('-topmost', True)
self.root.lift()
self.root.focus_force()
self.root.after(50, lambda: self.root.attributes('-topmost', False))
print("Window restored successfully")
except Exception as e:
print(f"Fehler beim Wiederherstellen: {e}")
def quit_app(self, icon, item):
"""Beendet die Anwendung."""
print("Quitting app")
if self.tray_icon:
self.tray_icon.stop()
self.root.destroy()
def bind_events(self):
"""Bindet Events für Drag und Resize."""
self.root._moving = False
self.root._resizing = False
def start_move(event):
if isinstance(event.widget, (tk.Entry, tk.Text)):
return
self.root._drag_x = event.x_root
self.root._drag_y = event.y_root
# Vereinfachte Drag-Logik (ohne Resize für Einfachheit)
self.root._moving = True
def do_move(event):
if self.root._moving:
dx = event.x_root - self.root._drag_x
dy = event.y_root - self.root._drag_y
x = self.root.winfo_x() + dx
y = self.root.winfo_y() + dy
self.root.geometry(f"+{x}+{y}")
self.root._drag_x = event.x_root
self.root._drag_y = event.y_root
def stop_move(event):
self.root._moving = False
# Bindings
self.canvas.bind('<ButtonPress-1>', start_move)
self.canvas.bind('<B1-Motion>', do_move)
self.canvas.bind('<ButtonRelease-1>', stop_move)
self.root.bind('<ButtonPress-1>', start_move)
self.root.bind('<B1-Motion>', do_move)
self.root.bind('<ButtonRelease-1>', stop_move)
self.inner_frame.bind('<ButtonPress-1>', start_move)
self.inner_frame.bind('<B1-Motion>', do_move)
self.inner_frame.bind('<ButtonRelease-1>', stop_move)
def run(self):
"""Startet die GUI-Schleife und die Zeitüberprüfung."""
self.check_alarm()
self.root.mainloop()
if __name__ == "__main__":
app = AlarmClock()
app.run()