-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwork_timer.py
More file actions
2585 lines (2199 loc) · 98.5 KB
/
Copy pathwork_timer.py
File metadata and controls
2585 lines (2199 loc) · 98.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import time
from datetime import datetime, timedelta
import os
import sys
import winreg as reg
from tkinter import font as tkfont
import csv
import calendar
from PIL import Image, ImageTk, ImageDraw, ImageFont
import pystray
import threading
import keyboard
from pathlib import Path
import shutil
import watchdog.observers
import watchdog.events
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from user_manager import UserManager
from login_window import LoginWindow
from cloud_sync import CloudSync
import winsound # 添加音效支持
try:
from playsound import playsound # 添加更多音效支持
PLAYSOUND_AVAILABLE = True
except ImportError:
PLAYSOUND_AVAILABLE = False
print("playsound库未安装,将使用系统默认音效")
class CloudConfig:
def __init__(self):
self.config_file = 'cloud_config.json'
self.default_config = {
'sync_enabled': False,
'sync_path': '',
'last_sync_time': None,
'device_id': None
}
self.load_config()
def load_config(self):
try:
with open(self.config_file, 'r') as f:
self.config = json.load(f)
except FileNotFoundError:
self.config = self.default_config
self.save_config()
def save_config(self):
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=4)
def get(self, key):
return self.config.get(key, self.default_config.get(key))
def set(self, key, value):
self.config[key] = value
self.save_config()
def setup_device_id(self):
if not self.get('device_id'):
import uuid
self.set('device_id', str(uuid.uuid4()))
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, app):
self.app = app
self.last_modified = 0
self.cooldown = 1 # 冷却时间(秒)
def on_modified(self, event):
if event.src_path.endswith('work_time.json'):
current_time = time.time()
# 检查是否在冷却期内
if current_time - self.last_modified > self.cooldown:
self.last_modified = current_time
self.app.handle_external_data_change()
class Settings:
def __init__(self):
self.config_file = 'settings.json'
self.default_settings = {
'opacity': 0.75,
'daily_goal': 8 * 3600, # 8小时
'auto_start': True,
'show_seconds': True,
'always_on_top': False, # 默认不置顶
'theme': 'dark', # 默认使用深色主题
'timer_mode': 'up', # 默认使用正计时模式,'up'为正计时,'down'为倒计时
'hotkeys': {
'toggle_timer': 'ctrl+shift+space',
'show_hide': 'ctrl+shift+h'
}
}
self.load_settings()
def load_settings(self):
try:
with open(self.config_file, 'r') as f:
self.settings = json.load(f)
except FileNotFoundError:
self.settings = self.default_settings
self.save_settings()
def save_settings(self):
with open(self.config_file, 'w') as f:
json.dump(self.settings, f, indent=4)
def get(self, key):
return self.settings.get(key, self.default_settings.get(key))
def set(self, key, value):
self.settings[key] = value
self.save_settings()
class WorkTimer:
# 深色主题颜色
DARK_THEME = {
'bg': '#2c2c2e',
'fg': '#ffffff',
'fg_secondary': '#98989d',
'button_bg': '#2c2c2e',
'button_hover': '#3a3a3c',
'entry_bg': '#3a3a3c',
'progress_bg': '#3a3a3c',
'progress_fg': '#0a84ff'
}
# 浅色主题颜色
LIGHT_THEME = {
'bg': '#f2f2f7',
'fg': '#000000',
'fg_secondary': '#666666',
'button_bg': '#f2f2f7',
'button_hover': '#e5e5ea',
'entry_bg': '#ffffff',
'progress_bg': '#e5e5ea',
'progress_fg': '#007aff'
}
def __init__(self):
self.settings = Settings()
self.user_manager = UserManager()
self.root = tk.Tk()
self.root.title("Pimer") # 修改软件名称
# 初始化音效管理器
self.sound_manager = SoundManager()
# 立即隐藏主窗口,防止出现半透明白色窗口
self.root.withdraw()
# 设置窗口样式
self.root.attributes('-topmost', self.settings.get('always_on_top'))
self.root.attributes('-alpha', self.settings.get('opacity'))
self.root.overrideredirect(True)
self.root.attributes('-transparentcolor', '#000001') # 特殊的透明色值
# 初始化置顶状态
self.topmost = self.settings.get('always_on_top')
# 创建数据目录
self.data_dir = Path('data')
self.data_dir.mkdir(exist_ok=True)
# 初始化变量
self.setup_variables()
# 加载图标
self.load_icons()
# 绑定事件
self.bind_events()
# 创建托盘图标(提前创建,避免quit_app中的错误)
self.setup_tray()
# 设置文件路径(提前设置,避免备份时的错误)
self.setup_file_paths()
# 显示登录窗口或直接加载数据
if not self.user_manager.is_logged_in():
self.show_login_window()
else:
self.on_login_success()
def show_login_window(self):
"""显示登录窗口"""
login_window = LoginWindow(self.root, self.user_manager, self.on_login_success)
# 主窗口已经在__init__中隐藏,这里不需要再次隐藏
# self.root.withdraw() # 隐藏主窗口
self.root.wait_window(login_window.window) # 等待登录窗口关闭
if not self.user_manager.is_logged_in():
self.quit_app() # 如果未登录,退出应用
def on_login_success(self):
"""登录成功回调"""
# 创建一个变量来控制是否显示加载窗口
self.loading_completed = False
self.loading_window = None
# 使用线程执行耗时操作,避免界面卡死
def load_app():
try:
# 重新设置文件路径(确保使用正确的用户目录)
self.setup_file_paths()
# 初始化云同步
if self.user_manager.is_logged_in():
username = self.user_manager.get_current_user()
self.cloud_sync = CloudSync(username)
print(f"云同步已初始化,状态:{'已连接' if self.cloud_sync.is_connected else '未连接'}")
# 加载数据
self.load_data()
# 设置UI和热键
self.setup_ui()
self.setup_hotkeys()
# 标记加载完成
self.loading_completed = True
# 如果加载窗口已经显示,则关闭它
if self.loading_window and self.loading_window.winfo_exists():
self.loading_window.destroy()
# 显示主窗口
self.root.deiconify()
# 开始更新计时器
self.update_timer()
except Exception as e:
# 标记加载完成(虽然是出错完成)
self.loading_completed = True
# 如果加载窗口已经显示,则显示错误信息
if self.loading_window and self.loading_window.winfo_exists():
loading_label = self.loading_window.nametowidget(".loading_frame.loading_label")
loading_label.config(text=f"加载失败: {str(e)}")
# 3秒后关闭加载窗口
self.loading_window.after(3000, self.loading_window.destroy)
else:
# 如果加载窗口未显示,则直接显示错误消息
messagebox.showerror("加载失败", f"加载应用程序时出错: {e}")
print(f"加载应用程序时出错: {e}")
# 启动加载线程
loading_thread = threading.Thread(target=load_app, daemon=True)
loading_thread.start()
# 3秒后检查是否需要显示加载窗口
def check_loading_status():
if not self.loading_completed:
# 如果3秒后仍未加载完成,显示加载窗口
self.show_loading_window()
# 3秒后检查加载状态
self.root.after(3000, check_loading_status)
def show_loading_window(self):
"""显示加载窗口"""
# 如果已经加载完成,不显示加载窗口
if self.loading_completed:
return
# 创建加载窗口
self.loading_window = tk.Toplevel(self.root)
self.loading_window.title("Pimer - loading")
# 设置与主窗口相同的位置和大小
self.loading_window.geometry('500x350+50+50') # 与主窗口相同的大小和位置
self.loading_window.resizable(False, False)
# 获取当前主题
theme = self.settings.get('theme')
colors = self.DARK_THEME if theme == 'dark' else self.LIGHT_THEME
self.loading_window.configure(bg=colors['bg'])
# 使加载窗口置于顶层
self.loading_window.attributes('-topmost', True)
# 居中显示加载提示
loading_frame = tk.Frame(self.loading_window, bg=colors['bg'], name="loading_frame")
loading_frame.pack(expand=True, fill="both", padx=20, pady=20)
loading_label = tk.Label(
loading_frame,
text="loading...",
font=("Microsoft YaHei", 18, "bold"),
fg=colors['fg'],
bg=colors['bg'],
name="loading_label"
)
loading_label.pack(pady=(50, 20))
# 添加进度条
progress = ttk.Progressbar(loading_frame, mode="indeterminate", length=400)
progress.pack(pady=30)
progress.start(10) # 启动进度条动画
# 确保窗口显示在前台
self.loading_window.lift()
self.loading_window.focus_force()
self.loading_window.update()
icon_path = "pig_nose_icon.ico"
if os.path.exists(icon_path):
self.loading_window.iconbitmap(icon_path)
def setup_file_paths(self):
"""设置文件路径"""
if self.user_manager.is_logged_in():
username = self.user_manager.get_current_user()
self.user_manager.ensure_user_data_dir(username)
self.data_file = self.user_manager.get_user_data_file(username)
else:
# 默认数据文件路径
self.data_file = Path('data/work_time.json')
# 确保目录存在
self.data_file.parent.mkdir(exist_ok=True)
def setup_file_watcher(self):
"""设置文件监听"""
if self.user_manager.is_logged_in():
username = self.user_manager.get_current_user()
self.observer = Observer()
self.event_handler = FileChangeHandler(self)
self.observer.schedule(
self.event_handler,
str(self.data_file.parent),
recursive=False
)
self.observer.start()
def handle_external_data_change(self):
"""处理外部数据变化"""
if not hasattr(self, 'is_saving'): # 避免处理自己的保存操作
self.is_saving = True
try:
self.merge_data()
self.update_display()
finally:
self.is_saving = False
def merge_data(self):
"""合并数据"""
try:
# 读取当前内存中的数据
current_data = {
str(self.today): {
'accumulated_time': self.accumulated_time,
'is_running': self.is_running,
'start_time': self.start_time if self.start_time else None
}
}
# 读取文件中的数据
with open(self.data_file, 'r') as f:
file_data = json.load(f)
# 合并数据
for date, data in file_data.items():
if date not in current_data:
current_data[date] = data
elif date == str(self.today):
# 对于今天的数据,保留较大的累计时间
if isinstance(data, dict) and isinstance(current_data[date], dict):
if data['accumulated_time'] > current_data[date]['accumulated_time']:
current_data[date] = data
self.accumulated_time = data['accumulated_time']
# 保存合并后的数据
with open(self.data_file, 'w') as f:
json.dump(current_data, f, indent=4)
except Exception as e:
print(f"合并数据时出错:{e}")
def update_display(self):
"""更新时间显示"""
if not self.is_running:
return
# 计算总秒数
total_seconds = self.accumulated_time
if self.start_time:
total_seconds += time.time() - self.start_time
# 根据计时模式显示时间
timer_mode = self.settings.get('timer_mode')
if timer_mode == 'up': # 正计时模式
# 计算时分秒
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
# 更新时间标签
if self.settings.get('show_seconds'):
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}:{seconds:02d}")
else:
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}")
else: # 倒计时模式
# 获取目标时间(小时)
try:
target_hours = float(self.target_time_var.get())
target_seconds = target_hours * 3600
# 计算剩余时间
remaining_seconds = max(0, target_seconds - total_seconds)
# 计算时分秒
hours = int(remaining_seconds // 3600)
minutes = int((remaining_seconds % 3600) // 60)
seconds = int(remaining_seconds % 60)
# 更新时间标签
if self.settings.get('show_seconds'):
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}:{seconds:02d}")
else:
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}")
# 如果倒计时结束,停止计时器并显示庆祝
# 只有当焦点不在目标输入框上时才检查
if remaining_seconds <= 0 and self.is_running and self.root.focus_get() != self.target_entry:
# 避免重复触发
if not hasattr(self, 'countdown_completed') or not self.countdown_completed:
self.countdown_completed = True
# 显示庆祝动画
self.show_celebration(is_target_completed=True)
# 自动增加目标时间1小时,与正计时模式一致
new_target = target_hours + 1.0
if new_target > 12: # 限制最大时间为12小时
new_target = 12.0
self.target_time_var.set(f'{new_target:.2f}')
# 停止计时器
# self.toggle_timer()
except (ValueError, AttributeError) as e:
print(f"倒计时模式计算时间出错: {e}")
# 出错时显示00:00:00
self.time_label.configure(text="00:00:00")
# 更新进度条
self.update_progress(total_seconds)
# 检查是否达到目标时间 - 只有当焦点不在目标输入框上时才检查
# 在正计时模式下才检查目标完成情况
if timer_mode == 'up' and self.root.focus_get() != self.target_entry:
try:
target_hours = float(self.target_time_var.get())
target_seconds = target_hours * 3600
# 检查是否完成目标
if total_seconds >= target_seconds and target_hours > 0:
# 避免重复触发庆祝
if not hasattr(self, 'target_completed') or not self.target_completed:
self.target_completed = True
# 显示庆祝动画
self.show_celebration(is_target_completed=True)
# 自动增加目标时间1小时
new_target = target_hours + 1.0
if new_target > 12: # 限制最大时间为12小时
new_target = 12.0
self.target_time_var.set(f'{new_target:.2f}')
# 更新进度条
self.update_progress()
else:
# 如果之前完成过目标,但现在目标变更了,重置标记
if hasattr(self, 'target_completed') and self.target_completed:
self.target_completed = False
except (ValueError, AttributeError) as e:
print(f"检查目标完成时出错: {e}")
# 每秒更新一次
self.root.after(1000, self.update_display)
def load_data(self):
"""加载数据(优先从云端同步)"""
try:
if hasattr(self, 'cloud_sync') and self.cloud_sync.is_connected:
# 尝试从云端同步数据
cloud_data = self.cloud_sync.sync_data()
if cloud_data:
current_date = datetime.now().date()
# 检查是否是新的一天
if str(current_date) not in cloud_data:
# 新的一天从零开始
self.accumulated_time = 0
self.is_running = False
self.start_time = None
else:
# 直接使用云端数据
today_data = cloud_data[str(current_date)]
if isinstance(today_data, (int, float)):
self.accumulated_time = today_data
self.is_running = False
self.start_time = None
else:
# 直接使用云端数据中的累计时间
self.accumulated_time = today_data['accumulated_time']
self.is_running = today_data['is_running']
if self.is_running and today_data['start_time']:
elapsed = time.time() - today_data['start_time']
self.accumulated_time += elapsed
self.start_time = time.time()
else:
self.start_time = None
self.is_running = False
# 设置当前日期
self.today = current_date
# 将云端数据保存到本地
with open(self.data_file, 'w') as f:
json.dump(cloud_data, f, indent=4)
return
# 如果没有云端数据或云同步失败,使用本地数据
try:
with open(self.data_file, 'r') as f:
data = json.load(f)
current_date = datetime.now().date()
# 检查是否是新的一天
if str(current_date) not in data:
# 新的一天从零开始
self.accumulated_time = 0
self.is_running = False
self.start_time = None
else:
# 加载当天的数据
today_data = data[str(current_date)]
if isinstance(today_data, (int, float)):
self.accumulated_time = today_data
self.is_running = False
self.start_time = None
else:
self.accumulated_time = today_data['accumulated_time']
self.is_running = today_data['is_running']
if self.is_running and today_data['start_time']:
elapsed = time.time() - today_data['start_time']
self.accumulated_time += elapsed
self.start_time = time.time()
else:
self.start_time = None
self.is_running = False
# 设置当前日期
self.today = current_date
except FileNotFoundError:
# 文件不存在时初始化数据
self.accumulated_time = 0
self.is_running = False
self.start_time = None
self.today = datetime.now().date()
except Exception as e:
print(f"加载数据时出错: {e}")
# 出错时初始化数据
self.accumulated_time = 0
self.is_running = False
self.start_time = None
self.today = datetime.now().date()
# 保存当前状态
self.save_data()
# 立即更新显示,确保显示历史数据
if hasattr(self, 'time_label'):
self.update_display()
def save_data(self):
"""保存数据(同时保存到本地和云端)"""
if hasattr(self, 'is_saving') and self.is_saving:
return
self.is_saving = True
try:
# 读取现有数据
try:
with open(self.data_file, 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
# 更新当天的数据
data[str(self.today)] = {
'accumulated_time': self.accumulated_time,
'is_running': self.is_running,
'start_time': self.start_time if self.start_time else None
}
# 保存所有数据
with open(self.data_file, 'w') as f:
json.dump(data, f, indent=4)
# 同步到云端
if hasattr(self, 'cloud_sync'):
# 如果未连接,尝试重新连接
if not self.cloud_sync.is_connected and hasattr(self.cloud_sync, 'client'):
try:
self.cloud_sync.client.admin.command('ping')
self.cloud_sync.is_connected = True
print("MongoDB重新连接成功")
# 连接成功后立即更新状态栏
self.update_status_bar()
except Exception as e:
print(f"MongoDB重新连接失败: {e}")
# 如果已连接,上传数据
if self.cloud_sync.is_connected:
try:
self.cloud_sync.upload_data(data)
print("数据已上传到云端")
except Exception as e:
print(f"上传数据到云端失败: {e}")
self.cloud_sync.is_connected = False
# 连接失败后立即更新状态栏
self.update_status_bar()
finally:
self.is_saving = False
def load_icons(self):
# 使用彩色emoji图标
self.icons = {
'play': "▶️", # 彩色播放图标
'pause': "⏸️", # 彩色暂停图标
'reset': "🔄", # 彩色重置图标
'pin': "📌", # 彩色图钉图标
'unpin': "📍", # 彩色未置顶图标
'stats': "📊", # 彩色统计图标
'settings': "⚙️", # 彩色设置图标
'close': "❌" # 彩色关闭图标
}
def bind_events(self):
# 拖动和缩放事件绑定
self.root.bind('<Button-1>', self.start_move)
self.root.bind('<B1-Motion>', self.on_move)
self.root.bind('<ButtonRelease-1>', self.stop_move)
# 鼠标进入窗口边缘时改变光标
self.root.bind('<Motion>', self.check_resize_cursor)
def check_resize_cursor(self, event):
# 获取窗口大小
width = self.root.winfo_width()
height = self.root.winfo_height()
# 定义边缘区域(10像素)
edge = 10
# 检查鼠标是否在右下角
if width - edge <= event.x <= width and height - edge <= event.y <= height:
self.root.config(cursor="sizing") # 改变光标为缩放形状
self.resize_mode = True
else:
self.root.config(cursor="") # 恢复默认光标
self.resize_mode = False
def start_move(self, event):
if not hasattr(self, 'resize_mode') or not self.resize_mode:
# 记录鼠标相对于窗口的位置
self.x = event.x_root - self.root.winfo_x()
self.y = event.y_root - self.root.winfo_y()
def on_move(self, event):
if hasattr(self, 'resize_mode') and self.resize_mode:
# 计算新的宽度和高度
width = max(300, event.x_root - self.root.winfo_x())
height = max(150, event.y_root - self.root.winfo_y())
self.root.geometry(f'{width}x{height}')
elif hasattr(self, 'x') and hasattr(self, 'y'):
# 移动窗口
x = event.x_root - self.x
y = event.y_root - self.y
self.root.geometry(f'+{x}+{y}')
def stop_move(self, event):
# 清除拖动和缩放状态
if hasattr(self, 'x'): delattr(self, 'x')
if hasattr(self, 'y'): delattr(self, 'y')
self.resize_mode = False
self.root.config(cursor="")
def toggle_topmost(self):
self.topmost = not self.topmost
self.root.attributes('-topmost', self.topmost)
self.pin_button.configure(text=self.icons['pin'] if self.topmost else self.icons['unpin'])
# 保存置顶状态到设置
self.settings.set('always_on_top', self.topmost)
def minimize_window(self):
self.root.withdraw()
self.window_visible = False
def toggle_timer(self):
if self.is_running:
self.is_running = False
self.toggle_button.configure(text=self.icons['play'])
self.status_label.configure(text="Paused")
if self.start_time:
self.accumulated_time += time.time() - self.start_time
self.save_data()
else:
# 获取计时模式
timer_mode = self.settings.get('timer_mode')
# 在倒计时模式下,如果已经倒计时结束,需要重置
if timer_mode == 'down' and hasattr(self, 'countdown_completed') and self.countdown_completed:
# 重置倒计时
self.accumulated_time = 0
delattr(self, 'countdown_completed')
# 如果目标时间为0,设置为1小时
try:
target_hours = float(self.target_time_var.get())
if target_hours < 0:
self.target_time_var.set('1.00')
target_hours = 1.0
except ValueError:
self.target_time_var.set('1.00')
target_hours = 1.0
# 更新显示
try:
target_seconds = target_hours * 3600
hours = int(target_seconds // 3600)
minutes = int((target_seconds % 3600) // 60)
seconds = int(target_seconds % 60)
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}:{seconds:02d}")
except ValueError:
self.time_label.configure(text="00:00:00")
self.is_running = True
self.toggle_button.configure(text=self.icons['pause'])
self.status_label.configure(text="Working...")
self.start_time = time.time()
# 更新进度条
self.update_progress()
def update_progress(self, total_seconds=None):
"""更新进度条"""
try:
# 只有当焦点不在目标输入框上时才更新进度条
if self.root.focus_get() != self.target_entry:
# 获取目标时间(小时)
target_hours = float(self.target_time_var.get())
if target_hours < 0:
target_hours = 1.0
self.target_time_var.set('1.00')
# 转换为秒
target_seconds = target_hours * 3600
# 如果没有提供total_seconds,则计算当前累计时间
if total_seconds is None:
total_seconds = self.accumulated_time
if self.is_running and self.start_time:
total_seconds += time.time() - self.start_time
# 获取计时模式
timer_mode = self.settings.get('timer_mode')
# 计算进度百分比
if timer_mode == 'up': # 正计时模式
# 正计时模式下,进度是累计时间占目标时间的百分比
progress = min(100, (total_seconds / target_seconds) * 100)
else: # 倒计时模式
# 倒计时模式下,进度是已用时间占目标时间的百分比
remaining_seconds = max(0, target_seconds - total_seconds)
elapsed_seconds = target_seconds - remaining_seconds
progress = min(100, (elapsed_seconds / target_seconds) * 100)
# 更新进度条
self.progress['value'] = progress
except (ValueError, ZeroDivisionError) as e:
# 处理异常情况
print(f"更新进度条时出错: {e}")
self.target_time_var.set('1.00')
self.progress['value'] = 0
def validate_target_time(self, event=None):
"""验证目标时间输入"""
try:
# 获取输入值
value_str = self.target_time_var.get().strip()
# 只在按下回车键或失去焦点时处理
if event and (event.keysym == 'Return' or event.type == '9'): # Return或FocusOut
# 处理特殊情况:多个小数点
if value_str.count('.') > 1:
# 只保留第一个小数点
parts = value_str.split('.')
value_str = parts[0] + '.' + ''.join(parts[1:])
# 空值处理
if not value_str:
self.target_time_var.set('1.0')
value = 1.0
else:
# 尝试转换为浮点数
value = float(value_str)
# 验证范围
if value < 0.01:
value = 0.01
elif value > 12: # 限制最大时间为12小时
value = 12.0
# 格式化为两位小数
self.target_time_var.set(f'{value:.2f}')
# 获取计时模式
timer_mode = self.settings.get('timer_mode')
# 在倒计时模式下,如果不在运行状态,更新显示的时间
if timer_mode == 'down' and not self.is_running:
# 计算新的剩余时间
target_seconds = value * 3600
hours = int(target_seconds // 3600)
minutes = int((target_seconds % 3600) // 60)
seconds = int(target_seconds % 60)
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}:{seconds:02d}")
# 重置倒计时完成标记
if hasattr(self, 'countdown_completed'):
delattr(self, 'countdown_completed')
# 先移除焦点
self.root.focus()
# 使用after方法确保焦点已经转移后再更新进度条
self.root.after(10, self.update_progress)
return True
except ValueError as e:
# 处理无效输入,只在焦点移出或按下回车键时处理
if event and (event.type == '9' or event.keysym == 'Return'):
print(f"目标时间输入错误: {e}")
self.target_time_var.set('1.00')
self.root.focus()
self.root.after(10, self.update_progress)
return False
def reset_timer(self):
# 添加确认对话框
icon_path = "pig_nose_icon.ico"
if os.path.exists(icon_path):
self.root.iconbitmap(icon_path)
if not messagebox.askyesno("确认清零", "确定要清零今天的工作时长吗?"):
return
else:
print(f"图标文件不存在: {icon_path}")
if not messagebox.askyesno("确认清零", "确定要清零今天的工作时长吗?"):
return
if self.is_running:
self.toggle_timer()
self.accumulated_time = 0
self.start_time = None
self.save_data()
# 获取计时模式
timer_mode = self.settings.get('timer_mode')
# 根据计时模式设置重置后的显示
if timer_mode == 'up': # 正计时模式
self.time_label.configure(text="00:00:00")
else: # 倒计时模式
try:
target_hours = float(self.target_time_var.get())
target_seconds = target_hours * 3600
hours = int(target_seconds // 3600)
minutes = int((target_seconds % 3600) // 60)
seconds = int(target_seconds % 60)
self.time_label.configure(text=f"{hours:02d}:{minutes:02d}:{seconds:02d}")
except ValueError:
self.time_label.configure(text="00:00:00")
self.status_label.configure(text="Ready")
self.progress['value'] = 0
self.toggle_button.configure(text=self.icons['play']) # 确保显示播放图标
# 重置完成标记
if hasattr(self, 'target_completed'):
delattr(self, 'target_completed')
if hasattr(self, 'countdown_completed'):
delattr(self, 'countdown_completed')
# 重置小时检查变量
if hasattr(self, 'last_hour'):
delattr(self, 'last_hour')
if hasattr(self, 'last_remaining_hour'):
delattr(self, 'last_remaining_hour')
def add_to_startup(self):
script_path = os.path.abspath(sys.argv[0])
key_path = r"Software\\Microsoft\\Windows\\CurrentVersion\\Run"
try:
key = reg.OpenKey(reg.HKEY_CURRENT_USER, key_path, 0, reg.KEY_ALL_ACCESS)
reg.SetValueEx(key, "WorkTimer", 0, reg.REG_SZ, script_path)
reg.CloseKey(key)
return True
except WindowsError:
return False
def setup_ui(self):
# 获取当前主题
theme = self.settings.get('theme')
colors = self.DARK_THEME if theme == 'dark' else self.LIGHT_THEME
# 设置窗口样式和初始大小
self.root.configure(bg=colors['bg'])
self.root.geometry('500x350+50+50') # 减小窗口高度到350像素
# 创建自定义字体
self.time_font = tkfont.Font(family="Calibri", size=52, weight="bold")
self.status_font = tkfont.Font(family="Calibri", size=24)
self.button_font = tkfont.Font(family="Segoe UI Emoji", size=18)
self.input_font = tkfont.Font(family="Calibri", size=24, weight="bold")
# 设置主题样式
self.style = ttk.Style()
self.style.theme_use('clam')
# 配置自定义样式
self.style.configure(
'Custom.TFrame',
background=colors['bg']
)
# 时间显示样式
self.style.configure(
'Timer.TLabel',
background=colors['bg'],
foreground=colors['fg'],
font=self.time_font,
padding=5
)
# 状态标签样式
self.style.configure(
'Status.TLabel',
background=colors['bg'],
foreground=colors['fg_secondary'],
font=self.status_font
)
# 按钮样式
self.style.configure(
'Icon.TButton',
background=colors['button_bg'],
foreground=colors['fg'],
relief='flat',
borderwidth=0,
font=self.button_font
)
# 按钮悬停效果
self.style.map('Icon.TButton',
background=[('active', colors['button_hover'])],
foreground=[('active', colors['fg'])]
)
# 进度条样式
self.style.configure(
'Custom.Horizontal.TProgressbar',
troughcolor=colors['progress_bg'],
background=colors['progress_fg'],
thickness=10,
borderwidth=0,
relief='flat'
)
# 输入框样式
self.style.configure(
'Target.TEntry',
fieldbackground=colors['entry_bg'],
foreground=colors['fg'],
insertcolor=colors['fg'],
font=self.input_font,
padding=5