-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask_manager.py
2680 lines (2276 loc) · 104 KB
/
task_manager.py
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
import customtkinter as ctk
import json
from datetime import datetime
import sqlite3
from PIL import Image
import tkinter.font as tkFont
from PIL import ImageTk # 添加 ImageTk 的导入
import os
import sys
import webbrowser
def get_resource_path(relative_path):
""" 获取资源文件的绝对路径 """
try:
# PyInstaller创建临时文件夹,将路径存储在_MEIPASS中
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class CustomMenu(ctk.CTkFrame):
def __init__(self, master, text, commands, colors, **kwargs):
super().__init__(master, fg_color="transparent", **kwargs)
self.master = master # 保存主窗口引用
self.colors = colors
self.commands = commands
self.dropdown = None
# 创建菜单按钮
self.menu_button = ctk.CTkButton(
self,
text=text,
font=("微软雅黑", 11),
fg_color="transparent",
text_color=colors["text"],
hover_color=colors["hover"],
height=25,
width=60,
command=self.show_dropdown
)
self.menu_button.pack(fill="x")
def show_dropdown(self):
# 如果有其他打开的菜单,先关闭它们
for widget in self.master.winfo_children():
if isinstance(widget, CustomMenu) and widget != self:
if widget.dropdown is not None:
widget.hide_dropdown()
if self.dropdown is None:
# 获取菜单按钮位置
x = self.winfo_rootx()
y = self.winfo_rooty() + self.winfo_height()
# 创建下拉菜单窗口
self.dropdown = tk.Toplevel()
self.dropdown.withdraw() # 先隐藏窗口
self.dropdown.overrideredirect(True)
# 设置 Toplevel 窗口的背景色
self.dropdown.configure(bg=self.colors["sidebar"])
# 创建下拉菜单框架
menu_frame = ctk.CTkFrame(
self.dropdown,
fg_color=self.colors["sidebar"],
border_width=1,
border_color=self.colors["border"]
)
menu_frame.pack(fill="both", expand=True, padx=0, pady=0)
# 添加菜单项
for label, command in self.commands.items():
if label == "-": # 分隔线
separator = ctk.CTkFrame(
menu_frame,
height=1,
fg_color=self.colors["border"]
)
separator.pack(fill="x", padx=5, pady=2)
else:
btn = ctk.CTkButton(
menu_frame,
text=label,
font=("微软雅黑", 11),
fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"],
anchor="w",
height=30,
command=lambda c=command: self.execute_command(c)
)
btn.pack(fill="x", padx=1, pady=1)
# 设置窗口位置并显示
self.dropdown.geometry(f"+{x}+{y}")
self.dropdown.update_idletasks()
self.dropdown.deiconify()
self.dropdown.attributes('-topmost', True)
# 绑定事件
self.dropdown.bind("<Leave>", self.on_menu_leave)
self.winfo_toplevel().bind_all("<Button-1>", self.on_click_outside, "+")
else:
self.hide_dropdown()
def on_menu_leave(self, event):
"""处理鼠标离开菜单事件"""
if self.dropdown:
# 获取当前鼠标位置
x = self.dropdown.winfo_pointerx()
y = self.dropdown.winfo_pointery()
# 检查鼠标是否真的离开了菜单区域
menu_x = self.dropdown.winfo_x()
menu_y = self.dropdown.winfo_y()
menu_width = self.dropdown.winfo_width()
menu_height = self.dropdown.winfo_height()
# 只有当鼠标真的离开菜单区域时才隐藏
if not (menu_x <= x <= menu_x + menu_width and
menu_y <= y <= menu_y + menu_height):
self.dropdown.after(200, self.check_mouse_position)
def check_mouse_position(self):
"""检查鼠标位置,决定是否隐藏菜单"""
if self.dropdown:
x = self.dropdown.winfo_pointerx()
y = self.dropdown.winfo_pointery()
menu_x = self.dropdown.winfo_x()
menu_y = self.dropdown.winfo_y()
menu_width = self.dropdown.winfo_width()
menu_height = self.dropdown.winfo_height()
if not (menu_x <= x <= menu_x + menu_width and
menu_y <= y <= menu_y + menu_height):
self.hide_dropdown()
def on_click_outside(self, event):
"""处理点击其他区域事件"""
if self.dropdown:
x = event.x_root
y = event.y_root
menu_x = self.dropdown.winfo_x()
menu_y = self.dropdown.winfo_y()
menu_width = self.dropdown.winfo_width()
menu_height = self.dropdown.winfo_height()
if not (menu_x <= x <= menu_x + menu_width and
menu_y <= y <= menu_y + menu_height):
self.hide_dropdown()
def hide_dropdown(self, event=None):
"""隐藏下拉菜单"""
if self.dropdown:
try:
self.winfo_toplevel().unbind_all("<Button-1>")
self.dropdown.destroy()
except:
pass
finally:
self.dropdown = None
def execute_command(self, command):
"""执行菜单命令"""
if command:
self.hide_dropdown()
command()
def update_colors(self, colors):
"""更新菜单颜色"""
self.colors = colors
self.menu_button.configure(
text_color=colors["text"],
hover_color=colors["hover"]
)
class TaskManager:
def __init__(self, root):
self.root = root
self.version = "V1.2"
# 设置窗口图标
try:
# 加载并转换图标
icon_path = get_resource_path("logo.png")
icon_image = Image.open(icon_path)
# 创建临时ico文件
icon_image = icon_image.resize((32, 32)) # Windows图标推荐尺寸
# 如果图片是PNG格式且有透明通道,需要确保它有RGBA模式
if 'A' not in icon_image.mode:
icon_image = icon_image.convert('RGBA')
# 保存为临时ico文件
icon_image.save("temp_icon.ico", format='ICO', sizes=[(32, 32)])
# 设置窗口图标
self.root.iconbitmap("temp_icon.ico")
# 删除临时文件
os.remove("temp_icon.ico")
except Exception as e:
print(f"Error setting window icon: {str(e)}")
# 初始化数据库
self.init_database()
# 设置窗口基本属性
self.root.title(f"BoBoMaker 智能清单 {self.version}")
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# 确保窗口已创建
self.root.update_idletasks()
# 加载主题图标
self.theme_icons = {
"light": ctk.CTkImage(
light_image=Image.open(get_resource_path("icons/moon.png")),
dark_image=Image.open(get_resource_path("icons/moon.png")),
size=(20, 20)
),
"dark": ctk.CTkImage(
light_image=Image.open(get_resource_path("icons/sun.png")),
dark_image=Image.open(get_resource_path("icons/sun.png")),
size=(20, 20)
)
}
# 定义展开/收起符号
self.expand_symbols = {
"expanded": "▼",
"collapsed": "▶"
}
try:
import ctypes
from ctypes import windll, wintypes
# 获取窗口句柄
hwnd = windll.user32.GetParent(self.root.winfo_id())
# 定义窗口样式常量
GWL_STYLE = -16
GWL_EXSTYLE = -20
WS_CAPTION = 0x00C00000
WS_THICKFRAME = 0x00040000
WS_EX_APPWINDOW = 0x00040000
#口样式
style = windll.user32.GetWindowLongW(hwnd, GWL_STYLE)
# 移除标题栏和边框
style &= ~(WS_CAPTION | WS_THICKFRAME)
# 设置新样式
windll.user32.SetWindowLongW(hwnd, GWL_STYLE, style)
# 设置扩展样式,确保在任务栏显示
exstyle = windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
exstyle |= WS_EX_APPWINDOW
windll.user32.SetWindowLongW(hwnd, GWL_EXSTYLE, exstyle)
# 强制更新窗口
windll.user32.SetWindowPos(
hwnd, 0, 0, 0, 0, 0,
0x0002 | 0x0004 | 0x0020 # SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED
)
except Exception as e:
print(f"Error setting window style: {str(e)}")
# 设置主题
ctk.set_default_color_theme("blue")
# 定义亮色和暗色主题的颜色方案
self.theme_colors = {
"light": {
"bg": "#FFFFFF", # 纯白背景
"sidebar": "#F8F9FA", # 浅灰边栏
"accent": "#4A90E2", # 柔和的蓝色
"text": "#2C3E50", # 深颜色的字
"text_secondary": "#95A5A6",# 次要文字颜色
"border": "#E5E5E5", # 边框颜色
"hover": "#F1F5F9", # 悬停颜色
"completed": "#27AE60", # 完成状态色
"uncompleted": "#FFFFFF", # 未完成状态色
"titlebar": "#F8F9FA", # 标题栏背景色
"menubar": "#F8F9FA", # 菜单栏背景色
"container": "#F8F9FA", # 容器背景色
"selected": "#E6F0FF" # 选中项背景色
},
"dark": {
"bg": "#1A1B1E", # 深色背景
"sidebar": "#2D2D30", # 深色侧边栏
"accent": "#4A90E2", # 保持相同的强调色
"text": "#E0E0E0", # 更亮的文字颜色
"text_secondary": "#808080",# 次要文字颜色
"border": "#3E3E42", # 深色边框
"hover": "#3E3E42", # 深色悬停
"completed": "#2ECC71", # 亮色完成状态
"uncompleted": "#2D2D30", # 深色未完成状态
"titlebar": "#252526", # 更深的标题背景色
"menubar": "#252526", # 菜单背景色
"container": "#252526", # 容器背色
"selected": "#2D3748" # 选中项背景色
}
}
# 加载主题设置
self.load_theme_preference()
# 创建自定义标题栏
self.create_title_bar()
# 绑定窗口事件
self.root.bind("<Map>", self.on_map)
self.root.bind("<Unmap>", self.on_unmap)
# 加载创建任务数据
self.categories = {
"工作": [],
"个人": [],
"学习": [],
"其他": []
}
self.current_category = "工作"
self.selected_task = None
self.drag_data = {"widget": None, "y": 0}
self.drag_window = None
# 最后设置窗口样式并显示
self.setup_window()
# 初始化界面
self.setup_gui()
self.load_tasks()
# 添加窗口停靠相关的属性
self.is_docked = False
self.is_dragging = False # 添加拖动状态标志
self.dock_timer = None
self.hide_timer = None
self.show_timer = None
self.dock_height = 5 # 隐藏时露出的高度
self.dock_width = 350 # 使用固定的停靠宽度
self.original_geometry = None # 保存原始位置和大小
# 绑定鼠标进入和离开事件
self.root.bind("<Enter>", self.on_mouse_enter)
self.root.bind("<Leave>", self.on_mouse_leave)
def init_database(self):
"""初始化数据库"""
try:
self.conn = sqlite3.connect('bobomaker.db')
self.cursor = self.conn.cursor()
# 创建类别表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
position INTEGER NOT NULL
)
''')
# 创建任务表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER,
text TEXT NOT NULL,
completed BOOLEAN NOT NULL DEFAULT 0,
created_date TEXT NOT NULL,
completed_date TEXT,
FOREIGN KEY (category_id) REFERENCES categories (id)
)
''')
# 创建设置表
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
''')
self.conn.commit()
except Exception as e:
print(f"Database initialization error: {str(e)}")
def setup_gui(self):
# 主容器
self.main_frame = ctk.CTkFrame(self.root, fg_color=self.colors["bg"])
self.main_frame.pack(fill="both", expand=True)
# 创建自定义菜单栏
self.create_menu_bar()
# 要内容区域容器
main_content = ctk.CTkFrame(self.main_frame, fg_color="transparent")
main_content.pack(fill="both", expand=True, padx=10, pady=10)
# 左侧面板
self.sidebar = ctk.CTkFrame(main_content,
width=120, # 设置固定的初始宽度
fg_color=self.colors["sidebar"],
border_width=1,
border_color=self.colors["border"])
self.sidebar.pack(side="left", fill="y", padx=(0, 5))
self.sidebar.pack_propagate(False)
# 初始化侧边栏状态
self.is_animating = False
self.is_expanded = True
self.sidebar_width = 120
self.max_width = 120 # 在这里初始化 max_width
self.animation_id = None
# 创建标题栏框架并保存引用
self.title_bar_frame = ctk.CTkFrame(self.sidebar, fg_color="transparent")
self.title_bar_frame.pack(fill="x", pady=(15, 10))
# 类别标题
self.category_title = ctk.CTkLabel(
self.title_bar_frame,
text="任务类别",
text_color=self.colors["text"],
font=("微软雅黑", 13)
)
self.category_title.pack(side="left", padx=10)
# 添加展开/收起按钮
self.sidebar_toggle_btn = ctk.CTkButton(
self.title_bar_frame,
text="◀", # 使用左箭头表示可以收起
width=20,
height=20,
corner_radius=5,
fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"],
font=("微软雅黑", 12),
command=self.toggle_sidebar
)
self.sidebar_toggle_btn.pack(side="right", padx=5)
# 类别列表
self.category_frame = ctk.CTkFrame(self.sidebar, fg_color="transparent")
self.category_frame.pack(fill="both", expand=True, padx=10)
self.category_buttons = []
for category in self.categories:
btn = ctk.CTkButton(self.category_frame,
text=category,
command=None,
fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"],
anchor="w",
height=28,
font=("微软雅黑", 11))
btn.pack(fill="x", pady=2)
# 绑定菜单和按钮事件
btn.bind("<Button-3>", lambda e, c=category: self.show_category_menu(e, c))
btn.bind("<Button-1>", lambda e, b=btn, c=category: self.on_button_press(e, b, c))
btn.bind("<B1-Motion>", self.on_drag_motion)
btn.bind("<ButtonRelease-1>", self.on_button_release)
self.category_buttons.append(btn)
# 右侧任务区域
self.right_pane = ctk.CTkFrame(main_content,
fg_color=self.colors["bg"], # 使用主背景色
border_width=1,
border_color=self.colors["border"])
self.right_pane.pack(side="left", fill="both", expand=True, padx=(5, 0))
# 任务列表区域
self.task_frame = ctk.CTkFrame(self.right_pane,
fg_color=self.colors["sidebar"]) # 使用侧边栏颜色
self.task_frame.pack(side="left", fill="both", expand=True)
# 任务输入框 - 简样式
self.task_entry = ctk.CTkEntry(self.task_frame,
placeholder_text="添加任务...",
height=36,
font=("微软雅黑", 11),
border_color=self.colors["border"])
self.task_entry.pack(fill="x", padx=15, pady=(15, 10))
self.task_entry.bind('<Return>', self.add_task)
# 任务列表滚动区域
self.task_scroll = ctk.CTkScrollableFrame(self.task_frame,
fg_color=self.colors["bg"]) # 改用主背景色
self.task_scroll.pack(fill="both", expand=True, padx=20)
# 任务详情面板初始隐藏
self.detail_frame = ctk.CTkFrame(self.right_pane,
fg_color=self.colors["sidebar"],
width=300)
def select_category(self, category):
# 确保类别存在
if category in self.categories:
self.current_category = category
self.update_task_list()
self.update_category_list()
else:
# 如果类别不存在,选择第一个可用的类别
if self.categories:
self.current_category = next(iter(self.categories))
else:
# 如果没有类别,创建默认类别
self.categories = {
"工作": [],
"个人": [],
"学习": [],
"其他": []
}
self.current_category = "工作"
self.update_task_list()
self.update_category_list()
def add_task(self, event=None):
"""添加新任务"""
task_text = self.task_entry.get().strip()
if task_text:
try:
# 创建新任务
task = {
"text": task_text,
"completed": False,
"created_date": datetime.now().strftime("%Y-%m-%d %H:%M"),
"completed_date": None
}
# 添加到当前类别
if self.current_category not in self.categories:
self.categories[self.current_category] = []
self.categories[self.current_category].append(task)
# 清空输入框
self.task_entry.delete(0, "end")
# 保存到数据库
try:
# 获取类别ID
self.cursor.execute('SELECT id FROM categories WHERE name = ?',
(self.current_category,))
category_id = self.cursor.fetchone()
if category_id is None:
# 如果类别不存在,先创建类别
self.cursor.execute('''
INSERT INTO categories (name, position)
VALUES (?, (SELECT COALESCE(MAX(position), 0) + 1 FROM categories))
''', (self.current_category,))
category_id = self.cursor.lastrowid
else:
category_id = category_id[0]
# 插入任务
self.cursor.execute('''
INSERT INTO tasks (category_id, text, completed, created_date, completed_date)
VALUES (?, ?, ?, ?, ?)
''', (category_id, task["text"], task["completed"],
task["created_date"], task["completed_date"]))
self.conn.commit()
except Exception as e:
print(f"Error saving task to database: {str(e)}")
self.conn.rollback()
# 更新显示
self.update_task_list()
self.update_category_list()
except Exception as e:
print(f"Error adding task: {str(e)}")
def update_task_list(self):
# 清除现有任务
for widget in self.task_scroll.winfo_children():
widget.destroy()
tasks = self.categories[self.current_category]
completed_tasks = [t for t in tasks if t["completed"]]
uncompleted_tasks = [t for t in tasks if not t["completed"]]
# 创建未完成任务分组
if uncompleted_tasks:
self.create_task_section("未完成", uncompleted_tasks, False)
# 创建已完成任务分
if completed_tasks:
self.create_task_section("已完成", completed_tasks, True)
def update_category_list(self):
for btn, category in zip(self.category_buttons, self.categories):
tasks = self.categories[category]
completed = sum(1 for task in tasks if task["completed"])
total = len(tasks)
# 存储原始类别名称为按钮的属性
btn._category_name = category
btn.configure(text=f"{category} ({completed}/{total})")
if category == self.current_category:
btn.configure(fg_color=self.colors["accent"],
text_color="white",
hover_color=self.colors["accent"])
else:
btn.configure(fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"])
def save_tasks(self):
"""保存任务到数据库"""
try:
# 开始事务
self.cursor.execute('BEGIN TRANSACTION')
# 清空现有数据
self.cursor.execute('DELETE FROM tasks')
self.cursor.execute('DELETE FROM categories')
# 保存类别和任务
for position, (category_name, tasks) in enumerate(self.categories.items()):
# 插入类别(只插入一次)
self.cursor.execute(
'INSERT INTO categories (name, position) VALUES (?, ?)',
(category_name, position)
)
category_id = self.cursor.lastrowid
# 保存该类别下的所有任务
for task in tasks:
self.cursor.execute('''
INSERT INTO tasks (
category_id, text, completed,
created_date, completed_date
) VALUES (?, ?, ?, ?, ?)
''', (
category_id,
task['text'],
1 if task['completed'] else 0, # 确保布尔值正确保存
task['created_date'],
task['completed_date']
))
# 提交事务
self.conn.commit()
except Exception as e:
print(f"Error saving tasks: {str(e)}")
self.conn.rollback()
def load_tasks(self):
"""从数据库加载任务"""
try:
# 清空现有数据
self.categories = {}
# 加载所有类别
self.cursor.execute('''
SELECT id, name, position FROM categories
ORDER BY position
''')
categories = self.cursor.fetchall()
# 如果没有类别,创建默认类别
if not categories:
default_categories = ["工作", "个人", "学习", "其他"]
for i, category in enumerate(default_categories):
self.cursor.execute('''
INSERT INTO categories (name, position) VALUES (?, ?)
''', (category, i))
self.conn.commit()
# 重新加载类别
self.cursor.execute('''
SELECT id, name, position FROM categories
ORDER BY position
''')
categories = self.cursor.fetchall()
# 初始化类别字典
for category_id, category_name, _ in categories:
self.categories[category_name] = []
# 加载该类别的所有任务
self.cursor.execute('''
SELECT text, completed, created_date, completed_date
FROM tasks
WHERE category_id = ?
''', (category_id,))
tasks = self.cursor.fetchall()
for task_data in tasks:
self.categories[category_name].append({
'text': task_data[0],
'completed': bool(task_data[1]),
'created_date': task_data[2],
'completed_date': task_data[3]
})
# 设置当前类别
if not self.current_category or self.current_category not in self.categories:
self.current_category = next(iter(self.categories))
# 更新显示
self.update_category_list()
self.update_task_list()
except Exception as e:
print(f"Error loading tasks: {str(e)}")
# 使用默认类别
self.categories = {
"工作": [],
"个人": [],
"学习": [],
"其他": []
}
self.current_category = "工作"
self.update_category_list()
self.update_task_list()
# 重新创建所有类别按钮
self.repack_category_buttons()
def add_category(self):
dialog = ctk.CTkInputDialog(text="输入新类别名称:",
title="添加类别")
new_name = dialog.get_input()
if new_name and new_name not in self.categories:
self.categories[new_name] = []
btn = ctk.CTkButton(self.category_frame,
text=new_name,
command=lambda c=new_name: self.select_category(c),
fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"],
anchor="w",
height=28,
font=("微软雅黑", 11))
btn.pack(fill="x", pady=2)
self.category_buttons.append(btn)
self.save_tasks()
self.update_category_list()
def edit_category(self):
if not self.current_category:
return
dialog = ctk.CTkToplevel(self.root)
dialog.title("重命名类")
dialog.transient(self.root)
dialog.grab_set()
# 设置大小并居中
self.center_window(dialog, 400, 180)
# 类别名称标签
ctk.CTkLabel(dialog,
text="输入新的类别名称:",
font=("微软雅黑", 12)).pack(pady=(15, 5))
# 创建输入框并预填充当前类别名称
entry = ctk.CTkEntry(dialog, width=350)
entry.pack(padx=20, pady=5)
entry.insert(0, self.current_category) # 预填充当前类别名称
entry.select_range(0, 'end') # 选中所有文本
entry.focus() # 获取焦点
def save_changes():
new_name = entry.get().strip()
if new_name and new_name != self.current_category and new_name not in self.categories:
# 获取所有类别的顺序
categories = list(self.categories.items())
# 到要重命名的类别的索引
index = next(i for i, (cat, _) in enumerate(categories) if cat == self.current_category)
# 重命名类别,保持其任务列表不变
categories[index] = (new_name, self.categories[self.current_category])
# 重建类别字典,保持顺序
self.categories = dict(categories)
# 更新当前选中类别
if self.current_category == self.current_category:
self.current_category = new_name
# 重新创建按钮并更新显示
self.repack_category_buttons()
self.save_tasks()
dialog.destroy()
# 添加按钮
button_frame = ctk.CTkFrame(dialog, fg_color="transparent")
button_frame.pack(fill="x", padx=20, pady=(10, 15))
# 按钮器,于居中显示钮
buttons_container = ctk.CTkFrame(button_frame, fg_color="transparent")
buttons_container.pack(expand=True)
# 确定按钮
ctk.CTkButton(buttons_container,
text="确定",
command=save_changes,
width=80).pack(side="left", padx=10)
# 取消按钮
ctk.CTkButton(buttons_container,
text="取消",
command=dialog.destroy,
width=80).pack(side="left", padx=10)
def toggle_task(self, task_index):
"""切换任务状态"""
try:
# 获取当前类别的所有任务
tasks = self.categories[self.current_category]
# 确保任务索引有效
if 0 <= task_index < len(tasks):
task = tasks[task_index]
# 切换状态
task["completed"] = not task["completed"]
# 更新完成时间
if task["completed"]:
task["completed_date"] = datetime.now().strftime("%Y-%m-%d %H:%M")
else:
task["completed_date"] = None
# 保存更改
self.save_tasks()
# 更新显示
self.update_task_list()
self.update_category_list()
# 如果有详情面板打开,也需要更新它
if (hasattr(self, 'detail_frame') and
hasattr(self, 'current_detail_task') and
self.detail_frame.winfo_exists() and
self.current_detail_task == task):
self.hide_task_details()
except Exception as e:
print(f"Error toggling task: {str(e)}")
def create_task_section(self, title, tasks, is_completed=False):
# 创建分组框架
section_frame = ctk.CTkFrame(self.task_scroll,
fg_color="transparent")
section_frame.pack(fill="x", pady=(0, 15)) # 增加底部间距
# 创建标题行
header_frame = ctk.CTkFrame(section_frame,
fg_color=self.colors["sidebar"],
border_width=1,
border_color=self.colors["border"])
header_frame.pack(fill="x")
# 展开/收起按钮
expand_btn = ctk.CTkButton(header_frame,
text=self.expand_symbols["expanded"],
width=28,
height=28,
command=lambda: self.toggle_section(expand_btn, tasks_frame),
fg_color="transparent",
text_color=self.colors["text"],
hover_color=self.colors["hover"],
font=("微软雅黑", 12))
expand_btn.pack(side="left", padx=(2, 2), pady=2)
# 分组标题和任务数量
title_text = f"{title} ({len(tasks)})"
title_label = ctk.CTkLabel(header_frame,
text=title_text,
font=("微软雅黑", 14, "bold"), # 保持标题字体大小
text_color=self.colors["text"],
anchor="w")
title_label.pack(side="left", padx=(2, 5), pady=3)
# 任务表框架
tasks_frame = ctk.CTkFrame(section_frame,
fg_color="transparent")
tasks_frame.pack(fill="x", pady=(5, 0))
# 显示任务
for i, task in enumerate(tasks):
# 任务容器
task_frame = ctk.CTkFrame(tasks_frame,
fg_color="transparent")
task_frame.pack(fill="x", pady=(0, 8))
# 任务内容容器
content_frame = ctk.CTkFrame(task_frame,
fg_color=self.colors["sidebar"],
border_width=1,
border_color=self.colors["border"])
content_frame.pack(fill="x", padx=(25, 0))
# 任务状态指示条
status_bar = ctk.CTkFrame(content_frame,
width=3,
height=28, # 设置固定高度
fg_color=self.colors["accent"] if not task["completed"] else "#999999")
status_bar.pack(side="left") # 移除 fill="y"
status_bar.pack_propagate(False) # 保持固定大小
# 复选框
checkbox = ctk.CTkCheckBox(content_frame,
text="",
width=15,
height=15,
border_width=1,
corner_radius=7.5,
border_color=self.colors["border"] if not task["completed"] else self.colors["accent"],
fg_color=self.colors["accent"],
hover_color=self.colors["accent"],
checkmark_color="white",
checkbox_width=15,
checkbox_height=15)
checkbox.pack(side="left", padx=(10, 5))
# 设置初始状态
if task["completed"]:
checkbox.select()
else:
checkbox.deselect()
# 获取任务在原始列表中的索引
original_index = self.categories[self.current_category].index(task)
# 绑定命令
checkbox.configure(command=lambda idx=original_index: self.toggle_task(idx))
# 计算可用宽度
available_width = content_frame.winfo_width() - 60 # 减去状态条、复选框和内边距的宽度
# 使用 CTkFont 而不是 tkFont
task_font = ctk.CTkFont(
family="微软雅黑",
size=14,
slant="roman"
)
# 任务文本
text = task["text"]
if task["completed"]:
# 方法1:使用双重删除线
text = ''.join([char + '\u0336\u0336' for char in text])
# 或者方法2:使用粗删除线字符
# text = ''.join([char + '\u0335' for char in text]) # \u0335 是一个更粗的删除线字符
# 任务文本标签
label = ctk.CTkLabel(content_frame,
text=text,
font=task_font,
text_color="#AAAAAA" if task["completed"] else self.colors["text"],
wraplength=400, # 先设置一个初始值
justify="left",
anchor="w")
label.pack(side="left",
fill="x",
expand=True, # 改回 True,让标签能够占据可用空间
padx=(5, 10),
pady=(4, 4))
def update_wraplength(label=label, content_frame=content_frame):
try:
# 计算实际可用宽度
content_width = content_frame.winfo_width()
if content_width > 0:
# 减去左侧状态条、复选框和内边距的宽度
available_width = content_width - 60
if available_width > 0:
label.configure(wraplength=available_width)
# 强制更新布局
label.update_idletasks()
content_frame.update_idletasks()
# 删除这行,不要再次调度更新
# label.after(100, lambda: update_wraplength(label, content_frame))
except Exception as e:
print(f"Error updating wraplength: {str(e)}")
# 绑定大小变化事件
content_frame.bind('<Configure>', lambda e, l=label, c=content_frame: update_wraplength(l, c))
# 立即调用一次更新
self.root.after(10, lambda: update_wraplength(label, content_frame))
# 绑定事件
for widget in [content_frame, label]:
widget.bind("<Button-1>", lambda e, t=task, f=task_frame: self.show_task_details(t, f))
widget.bind("<Button-3>", lambda e, t=task, i=i: self.show_task_menu(e, t, i))