-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskWing.py
More file actions
2769 lines (2347 loc) · 109 KB
/
Copy pathTaskWing.py
File metadata and controls
2769 lines (2347 loc) · 109 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
# 学翼 - 智能化学习任务管理工具
# Copyright (C) 2025 TiantianYZJ
#
# 声明:
# 本程序遵循GPLv3协议:您可以在遵守许可证条款的前提下自由使用、修改和分发。
# 完整授权条款请参见项目根目录下的LICENSE文件。
# 更新日志
Version = "V1.1.3"
CHANGELOG = [
"V0.0.1-2025.01.19 1、“学翼”正式诞生,具备代办管理功能",
"V0.0.2-2025.01.19 1、添加【任务进度报告】,生成饼图显示任务完成情况",
"V0.0.3-2025.01.19 1、用户群体细分,包装为任务管理软件;2、建立数据库,实现重进数据不受影响;3、完成情况使用文字(已完成、未完成)",
"V0.1.0-2025.01.19 1、UI界面焕新,更加现代化;2、主窗口顶部增加时间显示;3、添加深色模式,自动根据时间切换",
"V0.1.1-2025.01.19 1、接入WindowsMessage API,实现消息系统层级推送",
"V0.1.2-2025.01.20 1、增加系统托盘图标,实现后台驻留;2、完成情况改用图标",
"V0.1.4-2025.01.20 1、增加窗口置顶选项;2、新增【设置】,可手动选择主题、配置开机自启动",
"V0.2.0-2025.01.21 1、页面布局重新排版,各功能区块界线更明显;2、为所有按钮添加图标;3、丰富系统托盘右键菜单",
"V0.2.1-2025.01.21 1、适配开发环境与封装环境,解决打包.exe后无法调用外部资源的问题",
"V0.2.2-2025.01.22 1、优化【统计报告】,数据更丰富、更直观;2、添加【关于程序】页面;3、开机自启动支持一键配置",
"V0.2.3-2025.01.23 1、更换WindowsMessage API库,解决兼容性问题",
"V0.2.4-2025.02.11 1、增加【AI智答】功能,接入DeepseekAPI,支持单次询问、自定义API Key等功能",
"V0.2.5-2025.02.12 1、实现对AImarkdown格式回答的渲染",
"V0.2.6-2025.02.14 1、新增【更新日志】;2、优化API设置界面布局",
"V0.2.7-2025.02.14 1、增加启动欢迎提示,同时提醒待完成任务项",
"V0.2.8-2025.02.15 1、【AI设置】添加【私有API配置教程】;2、【AI智答】支持选择服务提供商",
"V0.2.9-2025.02.15 1、【学习数据统计】任务状态分布情况细分,更加丰富直观;2、启动欢迎提示增加即将截止、已截止任务提醒",
"V0.3.0-2025.02.15 1、HTML渲染页面全面适配深色模式",
"V0.3.1-2025.02.15 1、【AI智答】支持设置回答显示方式;2、【API配置教程】改为用浏览器打开,更美观",
"V0.3.2-2025.02.15 1、【API配置教程】更换渲染风格,响应式布局",
"V0.3.3-2025.02.16 1、托盘右键菜单优化,新增【统计报告】选项",
"V1.0.0-2025.02.16 1、“学翼”1.0.0正式版发布!欢迎体验交流",
"V1.0.1-2025.02.16 1、优化部分窗口尺寸;2、优化通知提示;3、修复了一些已知BUG",
"V1.0.2-2025.02.16 1、修复了一些已知BUG",
"V1.0.3-2025.02.16 1、更换高清图标",
"V1.0.4-2025.02.20 1、优化【清空】代码逻辑;2、正式确定应用名:中文“学翼”,英文“TaskWing”",
"V1.0.5-2025.02.22 1、新增【专注】,计入统计报告,助力高效学习;2、重要按钮增加悬停提示;3、【设置】新增【删除所有数据】,并优化操作逻辑",
"V1.0.6-2025.02.22 1、因Deepseek关闭充值入口,【AI智答】暂停提供该渠道共享API,该渠道私有API不受影响;2、优化【专注】;3、优化【设置】",
"V1.0.7-2025.02.22 1、优化按钮名称;2、主页面字体调整,更显眼;3、【统计报告】优化数据统计逻辑;4、接入日期选择器控件,选择日期更直观",
"V1.0.8-2025.02.23 1、主题模式新增【跟随系统】;2、浏览器显示回答支持复杂数学公式;3、【专注】新增音量调节;4、【统计报告】优化防溢出",
"V1.0.9-2025.02.28 1、新增更新检测,从此更新更方便;2、重新设计关于页面;3、取消悬浮提示框的渐显渐隐效果,杜绝了闪烁BUG",
"V1.1.0-2025.03.02 1、恢复默认API;2、任务列表支持双击和右键操作;3、优化【AI智答】、【关于】;4、添加【通知管理】;5、支持显示AI思考内容;6、【AI智答】支持添加附件",
"V1.1.1-2025.03.08 1、修复【AI智答】附件解析bug;2、检测更新时显示更新时间;3、浏览器端AI回答适配更多数学公式",
"V1.1.2-2025.03.09 1、“学翼”LOGO形象升级;2、【关于】添加【支持一下】",
"V1.1.3-2025.03.09 1、任务栏托盘支持单机快速启动;2、修复了在线更新bug",
]
import random
import threading
import tkinter as tk
from tkinter import simpledialog
from tkinter import filedialog
import tkinter.font as tkFont
from tkinter import ttk, messagebox
import sqlite3
import webbrowser
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime
from time import *
import locale
import sys
import importlib
import os
import pystray
from PIL import Image, ImageTk
from pathlib import Path
import winshell
from win10toast import ToastNotifier
from openai import OpenAI
from tkhtmlview import HTMLLabel
import mistune
import requests
from flask import Flask, render_template
import pygame
from datetime import timedelta
from tkcalendar import Calendar
import darkdetect
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from docx import Document
from win32com.client import Dispatch
# 音频管理配置
def get_current_volume():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
return round(volume.GetMasterVolumeLevelScalar() * 100)
def set_system_volume(value):
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
volume.SetMasterVolumeLevelScalar(int(float(value))/100, None)
# Flask配置
flask_app = Flask(__name__, template_folder='templates', static_folder='static')
flask_app.config['TEMPLATES_AUTO_RELOAD'] = True
current_response_html = ""
users_question = ""
# 添加Flask路由
@flask_app.route('/ai-response')
def show_ai_response():
return render_template('ai_response.html',
user_question=users_question,
ai_response=current_response_html,
bg_color=judge_theme(1),
text_color=judge_theme(2))
@flask_app.route('/tutorial')
def show_tutorial():
return render_template(
'tutorial.html',
bg_color=judge_theme(1),
text_color=judge_theme(2)
)
def run_flask_server():
flask_app.run(port=5000, use_reloader=False)
# 判断时间段
clock = int(strftime("%H"))
def judge_time():
if (clock >= 0 and clock <= 4):
timenow = "晚上"
elif (clock >= 5 and clock <= 9):
timenow = "早上"
elif (clock >= 10 and clock <= 11):
timenow = "上午"
elif (clock >= 12 and clock <= 14):
timenow = "中午"
elif (clock >= 15 and clock <= 17):
timenow = "下午"
elif (clock >= 18 and clock <= 24):
timenow = "晚上"
return timenow
# 定义资源路径函数
def resource_path(relative_path):
try:
# PyInstaller打包后的临时目录
base_path = sys._MEIPASS
except AttributeError:
# 开发环境下的当前目录
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# WindowsMessage API
icon_path = os.path.abspath(resource_path("LOGO.ico"))
def sent_notice(t,m):
c.execute("SELECT enable_notifications FROM notice_settings")
if c.fetchone()[0]:
toaster = ToastNotifier()
toaster.show_toast(
title=t,
msg=m,
icon_path=icon_path,
duration=1,
threaded=True
)
return 0
# 切换窗口置顶状态
def toggle_topmost():
is_topmost = topmost_var.get()
root.attributes('-topmost', is_topmost)
# 设置默认编码为 utf-8
locale.setlocale(locale.LC_CTYPE, 'zh_CN.UTF-8')
importlib.reload(sys)
# 获取用户数据目录
user_data_dir = Path(os.getenv('APPDATA')) / "TaskWing"
user_data_dir.mkdir(exist_ok=True)
# 修改数据库连接路径
db_path = user_data_dir / "TaskWing_data.db"
conn = sqlite3.connect(str(db_path))
c = conn.cursor()
# 创建任务表
c.execute('''CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
due_date TEXT,
rest_days INTEGER,
completed TEXT NOT NULL DEFAULT ' ')''')
c.execute("SELECT * FROM tasks")
tasks = c.fetchall()
conn.commit()
# 创建任务计数器表
c.execute('''CREATE TABLE IF NOT EXISTS task_counter (
total_tasks INTEGER DEFAULT 0)''')
conn.commit()
# 初始化计数器
c.execute("SELECT COUNT(*) FROM task_counter")
if c.fetchone()[0] == 0:
c.execute("INSERT INTO task_counter (total_tasks) VALUES (0)")
c.execute("SELECT * FROM task_counter")
task_counter = c.fetchall()
conn.commit()
# 主题设置
c.execute('''CREATE TABLE IF NOT EXISTS theme_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
theme_choice TEXT NOT NULL)''')
c.execute("SELECT * FROM theme_settings")
theme_settings = c.fetchall()
conn.commit()
# AI配置
c.execute('''CREATE TABLE IF NOT EXISTS ai_settings (
api_key TEXT,
default_model TEXT,
provider TEXT,
display_mode TEXT)''')
# 更新初始化数据
c.execute("SELECT COUNT(*) FROM ai_settings")
if c.fetchone()[0] == 0:
c.execute("INSERT INTO ai_settings (api_key, default_model, provider, display_mode) VALUES ('', 'deepseek-chat', 'Deepseek', 'window')")
ai_settings = c.fetchall()
conn.commit()
c.execute('''CREATE TABLE IF NOT EXISTS notice_settings (
enable_notifications INTEGER DEFAULT 1,
check_updates INTEGER DEFAULT 1)''')
# 更新初始化数据
c.execute("SELECT COUNT(*) FROM notice_settings")
if c.fetchone()[0] == 0:
c.execute("INSERT INTO notice_settings (enable_notifications, check_updates) VALUES (1, 1)")
notice_settings = c.fetchall()
conn.commit()
# 在数据库创建部分新增番茄钟记录表
c.execute('''CREATE TABLE IF NOT EXISTS pomodoro_records (
total_sessions INTEGER DEFAULT 0,
total_minutes INTEGER DEFAULT 0)''')
c.execute("SELECT COUNT(*) FROM pomodoro_records")
if c.fetchone()[0] == 0:
c.execute("INSERT INTO pomodoro_records (total_sessions, total_minutes) VALUES (0, 0)")
pomodoro_records = c.fetchall()
conn.commit()
c.execute('''CREATE TABLE IF NOT EXISTS api_usage
(date TEXT PRIMARY KEY, count INTEGER)''')
conn.commit()
# 检查读取的数据
print(tasks, task_counter, theme_settings, notice_settings, ai_settings, pomodoro_records)
# 获取任务总量、已完成数量和待完成数量
def get_num(mode):
conn.commit()
c.execute("SELECT COUNT(*) FROM tasks")
total_tasks = c.fetchone()[0]
c.execute("SELECT COUNT(*) FROM tasks WHERE completed='✅'")
completed_tasks = c.fetchone()[0]
if(mode == 1):
return total_tasks
elif(mode == 2):
return completed_tasks
elif(mode == 3):
return total_tasks - completed_tasks
c.execute("SELECT rest_days, completed FROM tasks")
all_tasks = c.fetchall()
completed = 0
pending = 0
upcoming = 0
expired = 0
for task in all_tasks:
rest_days, completed_status = task[0], task[1]
if completed_status == '✅':
pass
else:
if rest_days > 1:
pass
elif rest_days >= 0:
upcoming += 1
else:
expired += 1
if (get_num(1) == 0):
sent_notice(f"{judge_time()}好!", f"你没有任务哦,快去添加吧!")
else:
if (get_num(3) > 0):
if (upcoming > 0 and expired > 0):
sent_notice(f"{judge_time()}好!", f"你有{get_num(3)}个任务待完成,其中{expired}个已截止,{upcoming}个即将到期!")
elif (expired > 0):
sent_notice(f"{judge_time()}好!", f"你有{get_num(3)}个任务待完成,其中{expired}个已截止!")
elif (upcoming > 0):
sent_notice(f"{judge_time()}好!", f"你有{get_num(3)}个任务待完成,其中{upcoming}个即将到期!")
else:
sent_notice(f"{judge_time()}好!", f"你有{get_num(3)}个任务待完成")
elif (get_num(3) == 0):
sent_notice(f"{judge_time()}好!", f"你没有待完成的任务")
# 主窗口
root = tk.Tk()
root.title("学翼 - 您的一站式智能化学习平台")
width = 1000
height = 600
root.geometry(f"{width}x{height}")
# 创建一个Frame作为容器
frame = tk.Frame(root)
frame.grid(row=0, column=1, sticky="nsew")
# 设置网格的行和列权重
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
# 创建并启动Flask线程
flask_thread = threading.Thread(target=run_flask_server, daemon=True)
flask_thread.start()
# 设置窗口图标
def set_icon():
icon_image = Image.open(resource_path('LOGO.png'))
icon_photo = ImageTk.PhotoImage(icon_image)
root.iconphoto(True, icon_photo)
set_icon()
default_font = tkFont.nametofont("TkDefaultFont")
# 加载主题文件
azure_tcl_path = resource_path("azure.tcl")
root.tk.call("source", azure_tcl_path)
# 检查是否已经存在主题设置
c.execute("SELECT * FROM theme_settings")
theme_settings = c.fetchone()
# 如果没有主题设置,插入默认值
if not theme_settings:
c.execute("INSERT INTO theme_settings (theme_choice) VALUES ('跟随系统')")
conn.commit()
# 主题适配判断
def judge_theme(mode):
global theme
if theme == "light":
if mode == 1:
return "#ffffff"
elif mode == 2:
return "black"
elif theme == "dark":
if mode == 1:
return "#333333"
elif mode == 2:
return "white"
# 设置主题
def set_theme(theme_choice):
global theme
if theme_choice == "浅色模式":
root.tk.call("set_theme", "light")
theme = "light"
elif theme_choice == "深色模式":
root.tk.call("set_theme", "dark")
theme = "dark"
elif theme_choice == "自动切换":
clock = int(strftime("%H"))
if ((clock >= 0 and clock <= 4) or (clock >= 21 and clock <= 24)):
root.tk.call("set_theme", "dark")
theme = "dark"
else:
root.tk.call("set_theme", "light")
theme = "light"
elif theme_choice == "跟随系统":
if darkdetect.theme() == "Dark":
root.tk.call("set_theme", "dark")
theme = "dark"
else:
root.tk.call("set_theme", "light")
theme = "light"
# 重新应用表格样式
style = ttk.Style()
style.configure("Treeview.Heading", font=('Microsoft YaHei', 14))
style.configure("Treeview",font=('Microsoft YaHei', 12))
style.configure('Hyperlink.TLabel', foreground='blue', font=('Microsoft YaHei', 10, 'underline'), cursor='hand2')
style.configure("Large.TLabelframe.Label", font=('Microsoft YaHei', 12, 'bold'),background=judge_theme(1), foreground=judge_theme(2))
# 更新数据库中的主题设置
c.execute("UPDATE theme_settings SET theme_choice=? WHERE id=1", (theme_choice,))
conn.commit()
c.execute("SELECT theme_choice FROM theme_settings")
current_theme = c.fetchone()[0]
conn.commit()
set_theme(current_theme)
def update_theme():
c.execute("SELECT theme_choice FROM theme_settings")
cur_theme = c.fetchone()[0]
if cur_theme == "跟随系统":
set_theme(cur_theme)
conn.commit()
root.after(100, update_theme)
update_theme()
# Tooltip类
class Tooltip:
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tipwindow = None
self.after_id = None # 仅保留延迟定时器
self.widget.bind("<Enter>", self.schedule_show)
self.widget.bind("<Leave>", self.schedule_hide)
def schedule_show(self, event=None):
"""安排延迟显示"""
self.cancel_pending()
self.after_id = self.widget.after(500, self.showtip)
def schedule_hide(self, event=None):
"""立即隐藏"""
self.cancel_pending()
if self.tipwindow:
self.tipwindow.destroy()
self.tipwindow = None
def cancel_pending(self):
"""取消待执行操作"""
if self.after_id:
self.widget.after_cancel(self.after_id)
self.after_id = None
def showtip(self):
"""直接显示提示窗口"""
if self.tipwindow or not self.text:
return
# 定位计算
x = self.widget.winfo_rootx() + 25
y = self.widget.winfo_rooty() + 25
# 创建普通窗口
self.tipwindow = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
# 样式配置
bg_color = judge_theme(1)
text_color = judge_theme(2)
label = tk.Label(tw, text=self.text, justify='left',
background=bg_color, foreground=text_color,
relief='solid', borderwidth=1,
font=("Microsoft YaHei", 10))
label.pack()
def __del__(self):
"""对象销毁时清理资源"""
if self.tipwindow:
self.tipwindow.destroy()
# 更新剩余天数
def update_rest_days():
current_date = datetime.now().strftime("%Y/%m/%d")
c.execute("SELECT id, due_date FROM tasks")
tasks = c.fetchall()
for task in tasks:
task_id, due_date_str = task
due_date = datetime.strptime(due_date_str, "%Y/%m/%d")
current_date_obj = datetime.strptime(current_date, "%Y/%m/%d")
rest_days = (due_date - current_date_obj).days
c.execute("UPDATE tasks SET rest_days=? WHERE id=?", (rest_days, task_id))
conn.commit()
root.after(1000, update_rest_days) # 每秒更新
# 更新时间
def update_time():
timenow = judge_time()
stime = strftime("%Y/%m/%d %H:%M:%S")
def adjust_font_size(event):
height = event.height
if height / 2 > 55:
height = 55 * 2
elif height / 2 < 15:
height = 15 * 2
font_size = int(height / 2.5)
time_label.config(font=("Microsoft YaHei", font_size))
if not hasattr(root, 'time_label'):
time_label = ttk.Label(top_frame, text=f"{timenow}好,现在是{stime}", font=("Microsoft YaHei", 21))
time_label.place(relx=0.5, rely=0.5, anchor="center")
root.time_label = time_label
top_frame.bind("<Configure>", adjust_font_size)
else:
root.time_label.config(text=f"{timenow}好,现在是{stime}")
root.after(1000, update_time)
# 版本检测
def version_judge(parent):
github_api = 'https://api.github.com/repos/tiantianyzj/taskwing/releases/latest'
try:
res = requests.get(github_api).json()
except Exception as e:
if parent != root:
messagebox.showerror("网络错误", f"无法连接到GitHub,请检查网络连接。有可能是访问过于频繁,请稍后再试。\n错误信息:{e}", parent=parent)
return
get_version = res['name']# 最新版本
get_log = res['body']# 更新日志
get_time = f"{res['created_at'][0:10]} {res['created_at'][11:19]}"# 发布时间
if(Version != get_version):
if parent == root:
sent_notice("发现新版本", f"{Version} → {get_version}")
if messagebox.askokcancel("发现新版本", f"学翼 有新版本可用:{Version} → {get_version}\n发布时间:{get_time}\n\n更新内容:\n{get_log}\n\n单击【确定】立即下载", parent=parent):
get_down_url = res['assets'][0]['browser_download_url']# 下载链接
# 创建进度窗口
progress_window = tk.Toplevel(parent)
progress_window.title("下载进度")
progress_window.resizable(False, False)
progress_bar = ttk.Progressbar(progress_window, length=300, mode='determinate')
progress_bar.pack(padx=20, pady=20)
progress_label = ttk.Label(progress_window, text="0%")
progress_label.pack()
progress_window.transient(root)
progress_window.grab_set()
def download_with_progress():
try:
# 新增带进度条的下载代码
r = get_down_url
response = requests.get(r, stream=True)
file_name = r.split('/')[-1] # 从URL提取文件名
total_size = int(response.headers.get('content-length', 0))
# 添加时间计算相关变量
start_time = time()
last_update = 0 # 用于限制更新频率
# 设置下载路径为系统下载文件夹
download_dir = os.path.join(os.path.expanduser('~'), 'Downloads')
os.makedirs(download_dir, exist_ok=True) # 确保文件夹存在
file_name = r.split('/')[-1]
save_path = os.path.join(download_dir, file_name) # 完整保存路径
with open(save_path, 'wb') as f: # 修改保存路径
downloaded = 0
for chunk in response.iter_content(chunk_size=1024*128):
if chunk:
f.write(chunk)
downloaded += len(chunk)
progress = (downloaded / total_size) * 100
# 新增剩余时间计算
current_time = time()
elapsed = current_time - start_time
speed = downloaded / elapsed # 字节/秒
remaining = (total_size - downloaded) / speed if speed > 0 else 0
# 每0.2秒更新一次时间显示
if current_time - last_update >= 0.2 or progress >= 99.9:
# 格式化时间显示
remaining_str = f"{remaining//60:.0f}分{remaining%60:.0f}秒" if remaining > 60 else f"{remaining:.1f}秒"
progress_label.config(text=f"{progress:.1f}% (剩余 {remaining_str})")
last_update = current_time
# 更新进度条
progress_bar['value'] = progress
root.update_idletasks()
print(f"\r下载进度: {progress:.1f}%", end='')
progress_window.destroy()
sent_notice("下载完成", "请返回学翼进行下一步操作")
if messagebox.showinfo("下载完成", "下载完成!\n单击【确定】以进行安装,本程序将自动退出", parent=parent):
os.startfile(save_path) # 打开下载的文件
root.destroy() # 退出程序
except Exception as e:
if str(e) == "invalid command name \".!toplevel.!label\"":
messagebox.showerror("下载错误", "您手动关闭了下载窗口,下载被取消\n若为误触,可前往【设置】—【检查更新】重新运行该检查程序", parent=parent)
else:
messagebox.showerror("下载错误", f"下载失败,可能是服务器繁忙\n错误信息: {str(e)}", parent=parent)
progress_window.destroy()
# threading.Thread(target=download_with_progress, daemon=True).start
download_with_progress()
elif(Version == get_version and parent != root):
messagebox.showinfo("检查完成", f"当前已是最新版本\n当前版本:{Version}\n发布时间{get_time}\n\n此版本更新内容:\n{get_log}", parent=parent)
# 显示托盘图标
def create_tray_icon():
image = Image.open(os.path.abspath(resource_path("LOGO.ico")))
menu = (
pystray.MenuItem('主页', on_showing, default=True),
pystray.Menu.SEPARATOR,
pystray.MenuItem('AI智答', open_ai_assistant_window),
pystray.MenuItem('统计报告', open_progress_window),
pystray.Menu.SEPARATOR,
pystray.MenuItem('设置', open_settings_window),
pystray.MenuItem('关于应用', open_about_window),
pystray.Menu.SEPARATOR,
pystray.MenuItem('退出', on_closing)
)
if (get_num(1) == 0):
icon = pystray.Icon("LOGO", image, f"学翼(没有添加任务)", menu)
else:
if (get_num(3) > 0):
icon = pystray.Icon("LOGO", image, f"学翼({get_num(3)}个任务待完成)", menu)
elif (get_num(3) == 0):
icon = pystray.Icon("LOGO", image, f"学翼(所有任务已完成)", menu)
return icon
# 更新任务列表
def update_task_list():
task_list.delete(*task_list.get_children())
c.execute("SELECT * FROM tasks")
tasks = c.fetchall()
for task in tasks:
task_list.insert("", "end", values=task)
# 添加任务
def add_task():
current_date = datetime.now().strftime("%Y/%m/%d")
name = name_entry.get().strip()
due_date = date_entry.get().strip()
if not name:
messagebox.showerror("错误", "任务名称不能为空")
return
try:
# 先转换为datetime对象再进行计算
due_date_obj = datetime.strptime(due_date, "%Y/%m/%d")
current_date_obj = datetime.strptime(current_date, "%Y/%m/%d")
except ValueError:
messagebox.showerror("错误", "日期格式无效,请使用YYYY/MM/DD格式")
return
# 计算剩余天数(使用datetime对象)
rest_days = (due_date_obj - current_date_obj).days
# 插入任务并更新计数器
c.execute(
"INSERT INTO tasks (name, due_date, rest_days, completed) VALUES (?, ?, ?, ' ')",
(name, due_date, rest_days)
)
c.execute("UPDATE task_counter SET total_tasks = total_tasks + 1")
conn.commit()
# 重新编号任务ID
c.execute("SELECT id FROM tasks ORDER BY id")
ids = [row[0] for row in c.fetchall()]
for i, task_id in enumerate(ids):
c.execute("UPDATE tasks SET id=? WHERE id=?", (i + 1, task_id))
conn.commit()
update_task_list()
name_entry.delete(0, tk.END)
sent_notice("您添加了一个任务", name)
# 编辑任务
def edit_task():
selected = task_list.selection()
if not selected:
messagebox.showwarning("警告", "请选择一个任务进行修改。")
return
item = task_list.item(selected)
task_id, name, due_date, rest_days, completed, *extra_values = item['values']
edit_window = tk.Toplevel(root)
edit_window.title("修改任务")
edit_window.geometry("500x300")
edit_window.resizable(False, False)
# 主容器框架
main_frame = ttk.Frame(edit_window)
main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# ========== 任务信息部分 ==========
info_frame = ttk.LabelFrame(main_frame, text="任务详情", padding=10, style="Large.TLabelframe")
info_frame.pack(fill="x", pady=5)
# 任务名称
ttk.Label(info_frame, text="任务名称:").grid(row=0, column=0, sticky="w", padx=5)
name_entry = ttk.Entry(info_frame, width=40)
name_entry.bind("<Return>", lambda e: save_changes())
name_entry.insert(0, name)
name_entry.grid(row=0, column=1, columnspan=3, sticky="w", padx=5)
# ========== 截止日期部分 ==========
ttk.Label(info_frame, text="截止日期:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
# 创建日期输入框
date_entry = ttk.Entry(info_frame, width=12, font=('Microsoft YaHei', 9))
date_entry.insert(0, due_date) # 使用原日期初始化
date_entry.grid(row=1, column=1, sticky="w", padx=5, pady=10)
date_entry.bind("<Return>", lambda e: save_changes())
def set_edit_date():
def on_date_select():
date_entry.delete(0, tk.END)
date_entry.insert(0, cal.get_date())
top.grab_release()
top.destroy()
# 解析原始日期
init_year, init_month, init_day = map(int, due_date.split('/'))
top = tk.Toplevel(edit_window)
top.title("选择日期")
top.resizable(False, False)
top.transient(root)
top.grab_set()
cal = Calendar(top,
selectmode='day',
year=init_year,
month=init_month,
day=init_day,
date_pattern='y/mm/dd')
cal.pack(padx=10, pady=10)
ttk.Button(top, text="确定", command=on_date_select).pack(pady=10)
# 添加日期选择按钮
ttk.Button(info_frame, text="📅 选择", command=set_edit_date).grid(row=1, column=1, padx=120, pady=10)
Tooltip(info_frame.winfo_children()[4], "在日历中选择日期")
# ========== 任务状态部分 ==========
status_frame = ttk.LabelFrame(main_frame, text="任务状态", padding=10, style="Large.TLabelframe")
status_frame.pack(fill="x", pady=5)
completed_var = tk.BooleanVar(value=(completed == "✅"))
ttk.Checkbutton(
status_frame,
text="已完成",
variable=completed_var,
onvalue=True,
offvalue=False
).pack(side="left", padx=5)
# ========== 按钮部分 ==========
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(pady=10)
def save_changes():
current_date = datetime.now().strftime("%Y/%m/%d")
new_name = name_entry.get()
new_status = "✅" if completed_var.get() else " "
new_name = name_entry.get().strip()
new_date = date_entry.get().strip()
# 验证日期格式
try:
datetime.strptime(new_date, "%Y/%m/%d")
except ValueError:
messagebox.showerror("错误", "日期格式无效,请使用YYYY/MM/DD格式")
return
# 计算新剩余天数
current_date = datetime.now().date()
due_date_obj = datetime.strptime(new_date, "%Y/%m/%d").date()
new_rest_days = (due_date_obj - current_date).days
# 获取原始状态
c.execute("SELECT completed FROM tasks WHERE id=?", (task_id,))
current_status = c.fetchone()[0].strip()
if current_status.strip() == '' and new_status == "✅":
conn.commit()
total = get_num(1)
actual_completed = get_num(2)+1
remaining = get_num(3)-1
progress = round(actual_completed / total * 100, 2)
print(total, actual_completed, remaining)
if remaining == 0:
sent_notice("完成了所有任务,真厉害!", f"已完成{progress}%,共计{total}个任务")
else:
sent_notice("搞定一个任务,太棒了!", f"已完成{progress}%,还有{remaining}个任务待完成")
# 更新数据库
try:
c.execute(
"UPDATE tasks SET name=?, due_date=?, rest_days=?, completed=? WHERE id=?",
(new_name, new_date, new_rest_days, new_status, task_id)
)
conn.commit()
update_task_list()
edit_window.destroy()
except Exception as e:
messagebox.showerror("错误", f"保存失败:{str(e)}")
conn.rollback()
ttk.Button(
btn_frame,
text="💾 保存",
command=save_changes,
width=15
).pack(side="left", padx=10)
ttk.Button(
btn_frame,
text="↩️ 取消",
command=edit_window.destroy,
width=10
).pack(side="right", padx=10)
edit_window.transient(root)
edit_window.grab_set()
# 复制并粘贴任务
def copy_and_paste_task():
selected = task_list.selection()
if selected:
task_id = task_list.item(selected[0], "values")[0]
# 获取原始任务数据
c.execute("SELECT name, due_date, rest_days, completed FROM tasks WHERE id=?", (task_id,))
original = c.fetchone()
if original:
try:
new_name = f"{original[0]}(副本)"
c.execute("INSERT INTO tasks (name, due_date, rest_days, completed) VALUES (?, ?, ?, ?)",
(new_name, original[1], original[2], original[3]))
# 重新编号任务ID
c.execute("SELECT id FROM tasks ORDER BY id")
ids = [row[0] for row in c.fetchall()]
for i, task_id in enumerate(ids):
c.execute("UPDATE tasks SET id=? WHERE id=?", (i + 1, task_id))
conn.commit()
update_task_list()
sent_notice("您创建了一个任务副本", new_name)
except Exception as e:
messagebox.showerror("错误", f"复制失败\n错误信息:{str(e)}")
# 删除任务
def delete_task():
selected = task_list.selection()
if not selected:
messagebox.showwarning("警告", "请选择一个任务进行删除。")
return
item = task_list.item(selected)
task_id = item['values'][0]
# 删除关联统计记录
c.execute("DELETE FROM tasks WHERE id=?", (task_id,))
conn.commit()
# 重新编号
c.execute("SELECT id FROM tasks ORDER BY id")
ids = [row[0] for row in c.fetchall()]
for i, task_id in enumerate(ids):
c.execute("UPDATE tasks SET id=? WHERE id=?", (i + 1, task_id))
conn.commit()
update_task_list()
sent_notice("您删除了一个任务",f"目前还有{get_num(1)}个任务,{get_num(3)}个待完成")
# 确认清空任务列表的函数
def confirm_clear_tasks():
if messagebox.askokcancel("确认", "确定要清空任务列表吗?此操作不可恢复"):
c.execute("DELETE FROM tasks")
conn.commit()
update_task_list()
sent_notice("您清空了任务列表","任务列表清空成功")
def pomodoro_set_tasks():
# 获取选中的任务
selected = task_list.selection()
if not selected:
messagebox.showwarning("提示", "请先选择一个任务", parent=root)
return
# 获取实际任务ID
item = task_list.item(selected)
task_id = item['values'][0]
task_name = item['values'][1]
task_due = item['values'][2]
task_rest = item['values'][3]
# 创建设置窗口
setup_win = tk.Toplevel(root)
setup_win.title("番茄钟设置")
setup_win.geometry("600x700") # 增加窗口高度
setup_win.resizable(False, False)
setup_win.transient(root)
setup_win.grab_set()
# ========== 主容器 ==========
main_frame = ttk.Frame(setup_win)
main_frame.pack(fill='both', expand=True, padx=20, pady=15)
# ========== 设置区域 ==========
setup_frame = ttk.Frame(main_frame)
setup_frame.pack(fill='x', pady=10)
# 标题和输入框
header = ttk.Label(setup_frame,
text="🍅 番茄钟设置",
font=('Microsoft YaHei', 16, 'bold'),
foreground='#4fb9fe')
header.pack(pady=5)
info_frame = ttk.LabelFrame(setup_frame, text="任务信息", style="Large.TLabelframe", padding=15)
info_frame.pack(fill='both', expand=True, pady=10)
ttk.Label(info_frame,
text=f"""当前任务:{task_name}
截止日期:{task_due}
剩余天数:{task_rest}""",
font=('Microsoft YaHei', 12),
justify='left').grid(row=0, column=0, padx=5)
input_frame = ttk.LabelFrame(setup_frame, text="时长设置", style="Large.TLabelframe", padding=15)
input_frame.pack(fill='both', expand=True, pady=10)
ttk.Label(input_frame,
text="专注时长:",
font=('Microsoft YaHei', 12)).grid(row=0, column=0, padx=5)
time_var = tk.StringVar(value="25")
duration_combo = ttk.Combobox(
input_frame,
textvariable=time_var,
values=["5", "10", "15", "20", "25", "30", "45", "60", "90", "120",
"150", "180", "210", "240", "270", "300", "330", "360", "390",
"420", "450", "480", "510", "540", "570", "600"],
state="readonly",
font=('Microsoft YaHei', 11),
width=8
)
duration_combo.grid(row=0, column=1, padx=10)
ttk.Label(input_frame,
text="分钟",
font=('Microsoft YaHei', 12)).grid(row=0, column=2, padx=5)
# ========== 说明区域 ==========
desc_frame = ttk.LabelFrame(main_frame,
text="方法说明",
padding=15,
style="Large.TLabelframe")
desc_frame.pack(fill='both', expand=True, pady=10)
desc_text = """• 推荐使用方式:
1、选择25分钟专注单元
2、专注期间不处理其他事务
3、完成后休息5分钟
4、每完成4个番茄钟休息15-30分钟
• 注意事项:
1、遇到打断需重新开始计时
2、休息时间不要使用电子设备"""
ttk.Label(desc_frame,
text=desc_text,
font=('Microsoft YaHei', 10),
foreground='#7f8c8d',
justify='left').pack(anchor='w')
# ========== 按钮区域 ==========
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(pady=15)
def start_pomodoro():
setup_win.destroy()
show_pomodoro_interface(int(time_var.get()), task_id)
start_btn = ttk.Button(
btn_frame,
text="⌛️ 开始专注",
command=lambda:start_pomodoro(),
width=15,
style="Accent.TButton"
)
start_btn.pack(pady=5)
# 添加样式配置
style = ttk.Style()
style.configure("Accent.TButton",