forked from vancehuds/VanceCoursePro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_gui.py
More file actions
1862 lines (1507 loc) · 71 KB
/
main_gui.py
File metadata and controls
1862 lines (1507 loc) · 71 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
"""
Course Selection GUI
Main graphical interface for automated course selection.
"""
import tkinter as tk
from tkinter import messagebox, scrolledtext, simpledialog
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
import threading
import time
import json
import os
import webbrowser
from jwglxt_api import JwglxtAPI
from account_manager import AccountManager, Account
from task_manager import TaskManager, GrabTask, CourseInfo, TaskStatus
# Application constants
APP_NAME = "VanceCoursePro"
APP_VERSION = "v1.0"
class AccountDialog:
"""Dialog for adding or editing an account."""
def __init__(self, parent, title, name="", username="", password=""):
self.result = None
self.dialog = ttk.Toplevel(parent)
self.dialog.title(title)
self.dialog.geometry("400x280")
self.dialog.transient(parent)
self.dialog.grab_set()
# Center the dialog
self.dialog.update_idletasks()
x = parent.winfo_x() + (parent.winfo_width() - 400) // 2
y = parent.winfo_y() + (parent.winfo_height() - 250) // 2
self.dialog.geometry(f"400x280+{x}+{y}")
# Container
container = ttk.Frame(self.dialog)
container.pack(fill="both", expand=True, padx=20, pady=20)
# Header
header = ttk.Label(
container,
text=f"{'➕' if not name else '✏️'} {title}",
font=("Segoe UI", 12, "bold"),
bootstyle="primary"
)
header.pack(anchor="w", pady=(0, 15))
# Form
form = ttk.Frame(container)
form.pack(fill="x")
# Name
name_row = ttk.Frame(form)
name_row.pack(fill="x", pady=(0, 10))
ttk.Label(name_row, text="名称:", width=8).pack(side="left")
self.name_entry = ttk.Entry(name_row, width=30, font=("Segoe UI", 10))
self.name_entry.pack(side="left", fill="x", expand=True)
self.name_entry.insert(0, name)
# Username
username_row = ttk.Frame(form)
username_row.pack(fill="x", pady=(0, 10))
ttk.Label(username_row, text="学号:", width=8).pack(side="left")
self.username_entry = ttk.Entry(username_row, width=30, font=("Segoe UI", 10))
self.username_entry.pack(side="left", fill="x", expand=True)
self.username_entry.insert(0, username)
# Password
password_row = ttk.Frame(form)
password_row.pack(fill="x", pady=(0, 10))
ttk.Label(password_row, text="密码:", width=8).pack(side="left")
self.password_entry = ttk.Entry(password_row, width=30, font=("Segoe UI", 10), show="●")
self.password_entry.pack(side="left", fill="x", expand=True)
self.password_entry.insert(0, password)
# Buttons
btn_frame = ttk.Frame(container)
btn_frame.pack(fill="x", pady=(20, 0))
ttk.Button(
btn_frame,
text="取消",
command=self._on_cancel,
bootstyle="secondary"
).pack(side="right", padx=(8, 0))
ttk.Button(
btn_frame,
text="保存",
command=self._on_save,
bootstyle="success"
).pack(side="right")
self.dialog.wait_window()
def _on_save(self):
name = self.name_entry.get().strip()
username = self.username_entry.get().strip()
password = self.password_entry.get().strip()
if not name or not username or not password:
messagebox.showwarning("警告", "请填写所有字段", parent=self.dialog)
return
self.result = (name, username, password)
self.dialog.destroy()
def _on_cancel(self):
self.dialog.destroy()
class CourseSelectionApp:
"""Main application window with modern UI."""
def __init__(self, root):
self.root = root
self.root.title("VanceCoursePro")
self.root.geometry("1200x850")
self.root.minsize(1100, 750)
# Initialize managers
self.account_manager = AccountManager()
self.task_manager = TaskManager(self.account_manager)
# Set up task manager callbacks
self.task_manager.on_task_update = self._on_task_update
self.task_manager.on_task_success = self._on_task_success
self.task_manager.on_task_error = self._on_task_error
self.task_manager.on_log = self._on_task_log
# Current account (API session is managed by task_manager)
self.current_account: Account = None
self.courses = []
self.classes = []
self.current_page = 1
self._create_widgets()
self._load_accounts()
self._refresh_task_list()
def _create_card(self, parent, title):
"""Create a styled card container with title."""
# Outer container with padding
outer = ttk.Frame(parent)
# Card frame - use tk.LabelFrame to avoid ttkbootstrap padding issue with Python 3.14
card = tk.LabelFrame(
outer,
text=f" {title} "
)
card.pack(fill="both", expand=True)
# Inner container for padding
inner = ttk.Frame(card)
inner.pack(fill="both", expand=True, padx=15, pady=15)
return outer, inner
def _create_widgets(self):
"""Create all UI elements with modern styling."""
# Main container with padding
main_container = ttk.Frame(self.root)
main_container.pack(fill="both", expand=True, padx=15, pady=15)
# ========== HEADER ==========
header_frame = ttk.Frame(main_container)
header_frame.pack(fill="x", pady=(0, 15))
title_label = ttk.Label(
header_frame,
text=f"🎓 {APP_NAME}",
font=("Segoe UI", 18, "bold"),
bootstyle="primary"
)
title_label.pack(side="left")
version_label = ttk.Label(
header_frame,
text=APP_VERSION,
font=("Segoe UI", 10),
bootstyle="secondary"
)
version_label.pack(side="left", padx=(10, 0), pady=(8, 0))
# About button
self.about_btn = ttk.Button(
header_frame,
text="ℹ️ 关于",
command=self._on_about,
bootstyle="secondary-outline"
)
self.about_btn.pack(side="right")
# Settings button on the right
self.settings_btn = ttk.Button(
header_frame,
text="⚙️ 设置",
command=self._on_settings,
bootstyle="secondary-outline"
)
self.settings_btn.pack(side="right", padx=(0, 8))
# ========== MAIN LAYOUT (PanedWindow) ==========
# Vertical split: Content on Top, Logs on Bottom
main_paned = ttk.Panedwindow(main_container, orient="vertical")
main_paned.pack(fill="both", expand=True)
# Top Pane (Horizontal split: Courses vs Tasks)
top_paned = ttk.Panedwindow(main_paned, orient="horizontal")
main_paned.add(top_paned, weight=4)
# Left Frame (Courses)
left_frame = ttk.Frame(top_paned)
top_paned.add(left_frame, weight=3)
# Right Frame (Accounts + Tasks)
right_frame = ttk.Frame(top_paned)
top_paned.add(right_frame, weight=1)
# Bottom Frame (Logs)
bottom_frame = ttk.Frame(main_paned)
main_paned.add(bottom_frame, weight=1)
# ========== RIGHT SIDE: ACCOUNT & TASKS ==========
# 1. Account Management (Top of Right Side)
account_outer, account_card = self._create_card(right_frame, "🔐 账号管理")
account_outer.pack(fill="x", pady=(0, 10))
# Account management row
account_row = ttk.Frame(account_card)
account_row.pack(fill="x")
# Account selector (Compact)
row1 = ttk.Frame(account_row)
row1.pack(fill="x", pady=(0, 5))
ttk.Label(row1, text="账号").pack(side="left", padx=(0, 5))
self.account_combobox = ttk.Combobox(row1, width=18, state="readonly")
self.account_combobox.pack(side="left", fill="x", expand=True)
self.account_combobox.bind("<<ComboboxSelected>>", self._on_account_selected)
# Status indicator
self.status_frame = ttk.Frame(row1)
self.status_frame.pack(side="right")
self.status_dot = tk.Canvas(
self.status_frame,
width=10, height=10,
highlightthickness=0
)
self.status_dot.pack(side="left", padx=(5, 5))
self.status_dot.create_oval(2, 2, 10, 10, fill="gray", outline="")
# Account buttons (Row 2)
row2 = ttk.Frame(account_row)
row2.pack(fill="x")
self.add_account_btn = ttk.Button(row2, text="➕", width=3, command=self._on_add_account, bootstyle="secondary")
self.add_account_btn.pack(side="left", padx=(0, 2))
self.edit_account_btn = ttk.Button(row2, text="✏️", width=3, command=self._on_edit_account, bootstyle="secondary")
self.edit_account_btn.pack(side="left", padx=(0, 2))
self.delete_account_btn = ttk.Button(row2, text="🗑", width=3, command=self._on_delete_account, bootstyle="danger")
self.delete_account_btn.pack(side="left", padx=(0, 5))
self.login_btn = ttk.Button(row2, text="登录", width=6, command=self._on_login, bootstyle="success")
self.login_btn.pack(side="right")
self.status_label = ttk.Label(self.status_frame, text="未登录", bootstyle="secondary")
# 2. Task Management (Rest of Right Side)
task_outer, task_card = self._create_card(right_frame, "📋 抢课任务")
task_outer.pack(fill="both", expand=True)
# Task list treeview
task_tree_container = ttk.Frame(task_card)
task_tree_container.pack(fill="both", expand=True, pady=(0, 8))
task_columns = ("status", "course", "interval", "attempts", "message")
self.task_tree = ttk.Treeview(
task_tree_container,
columns=task_columns,
show="headings",
selectmode="browse",
height=4,
bootstyle="primary"
)
self.task_tree.heading("status", text="状态")
self.task_tree.heading("course", text="课程")
self.task_tree.heading("interval", text="间隔")
self.task_tree.heading("attempts", text="尝试")
self.task_tree.heading("message", text="消息")
self.task_tree.column("status", width=35, anchor="center")
self.task_tree.column("course", width=90)
self.task_tree.column("interval", width=35, anchor="center")
self.task_tree.column("attempts", width=35, anchor="center")
self.task_tree.column("message", width=100)
task_scrollbar = ttk.Scrollbar(task_tree_container, orient="vertical", command=self.task_tree.yview)
self.task_tree.configure(yscrollcommand=task_scrollbar.set)
self.task_tree.pack(side="left", fill="both", expand=True)
task_scrollbar.pack(side="right", fill="y")
self.task_tree.bind("<Double-1>", lambda e: self._on_edit_task())
# Task control buttons
task_btn_row = ttk.Frame(task_card)
task_btn_row.pack(fill="x")
self.start_task_btn = ttk.Button(task_btn_row, text="启动", width=4, command=self._on_start_task, bootstyle="success")
self.start_task_btn.pack(side="left", padx=(0, 2))
self.stop_task_btn = ttk.Button(task_btn_row, text="暂停", width=4, command=self._on_stop_task, bootstyle="warning")
self.stop_task_btn.pack(side="left", padx=(0, 2))
self.edit_task_btn = ttk.Button(task_btn_row, text="✏", width=3, command=self._on_edit_task, bootstyle="secondary")
self.edit_task_btn.pack(side="left", padx=(0, 2))
self.delete_task_btn = ttk.Button(task_btn_row, text="🗑", width=3, command=self._on_delete_task, bootstyle="danger")
self.delete_task_btn.pack(side="left", padx=(0, 5))
self.start_all_btn = ttk.Button(task_btn_row, text="全启", width=4, command=self._on_start_all_tasks, bootstyle="success-outline")
self.start_all_btn.pack(side="left", padx=(0, 2))
self.stop_all_btn = ttk.Button(task_btn_row, text="全停", width=4, command=self._on_stop_all_tasks, bootstyle="warning-outline")
self.stop_all_btn.pack(side="left")
self.task_count_label = ttk.Label(task_btn_row, text="0", bootstyle="secondary")
self.task_count_label.pack(side="right")
# ========== LEFT SIDE: COURSE SELECTION ==========
course_outer, course_card = self._create_card(left_frame, "📚 课程列表")
course_outer.pack(fill="both", expand=True)
# Control toolbar
toolbar = ttk.Frame(course_card)
toolbar.pack(fill="x", pady=(0, 12))
# Left side buttons
btn_left = ttk.Frame(toolbar)
btn_left.pack(side="left")
self.load_courses_btn = ttk.Button(btn_left, text="📥 加载列表", command=self._on_load_courses, state="disabled", bootstyle="info")
self.load_courses_btn.pack(side="left", padx=(0, 4))
self.load_more_btn = ttk.Button(btn_left, text="📄 更多", command=self._on_load_more_courses, state="disabled", bootstyle="info-outline")
self.load_more_btn.pack(side="left", padx=(0, 4))
self.load_all_btn = ttk.Button(btn_left, text="📦 全部", command=self._on_load_all_courses, state="disabled", bootstyle="info-outline")
self.load_all_btn.pack(side="left", padx=(0, 4))
ttk.Separator(btn_left, orient="vertical").pack(side="left", fill="y", padx=8)
self.load_all_details_btn = ttk.Button(btn_left, text="🔍 一键详情", command=self._on_load_all_details, state="disabled", bootstyle="primary")
self.load_all_details_btn.pack(side="left", padx=(0, 4))
self.load_details_only_btn = ttk.Button(btn_left, text="📋 仅详情", command=self._on_load_details_only, state="disabled", bootstyle="primary-outline")
self.load_details_only_btn.pack(side="left", padx=(0, 4))
# Right side - filters
filter_frame = ttk.Frame(toolbar)
filter_frame.pack(side="right")
self.tab_combobox = ttk.Combobox(filter_frame, width=10, state="readonly")
self.tab_combobox.pack(side="left", padx=(0, 8))
self.search_entry = ttk.Entry(filter_frame, width=15, font=("Segoe UI", 10))
self.search_entry.pack(side="left")
self.search_entry.bind("<Return>", lambda e: self._on_load_courses())
# Course Treeview with custom styling
tree_container = ttk.Frame(course_card)
tree_container.pack(fill="both", expand=True, pady=(0, 12))
columns = ("kch_id", "kcmc", "xf", "yxzt", "jxb_mc", "jsxx", "yxzrs")
display_columns = ("kch_id", "kcmc", "xf" , "jxb_mc", "jsxx", "yxzrs")
self.course_tree = ttk.Treeview(
tree_container,
columns=columns,
displaycolumns=display_columns,
show="headings",
selectmode="browse",
bootstyle="primary"
)
self.course_tree.heading("kch_id", text="代码")
self.course_tree.heading("kcmc", text="课程名称")
self.course_tree.heading("xf", text="学分")
self.course_tree.heading("yxzt", text="★是否已选")
self.course_tree.heading("jxb_mc", text="教学班")
self.course_tree.heading("jsxx", text="教师")
self.course_tree.heading("yxzrs", text="余量")
self.course_tree.column("kch_id", width=80, anchor="center")
self.course_tree.column("kcmc", width=180)
self.course_tree.column("xf", width=40, anchor="center")
self.course_tree.column("yxzt", width=30, anchor="center")
self.course_tree.column("jxb_mc", width=100)
self.course_tree.column("jsxx", width=80)
self.course_tree.column("yxzrs", width=60, anchor="center")
scrollbar = ttk.Scrollbar(tree_container, orient="vertical", command=self.course_tree.yview)
self.course_tree.configure(yscrollcommand=scrollbar.set)
self.course_tree.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
self.course_tree.bind("<<TreeviewSelect>>", self._on_course_select)
# Action buttons row
action_row = ttk.Frame(course_card)
action_row.pack(fill="x")
# Grab section
grab_section = ttk.Frame(action_row)
grab_section.pack(side="left")
self.add_task_btn = ttk.Button(grab_section, text="➕ 任务", command=self._on_add_task, state="disabled", bootstyle="success")
self.add_task_btn.pack(side="left", padx=(0, 6))
self.drop_btn = ttk.Button(grab_section, text="🗑 退选", command=self._on_drop, state="disabled", bootstyle="danger")
self.drop_btn.pack(side="left", padx=(0, 10))
self.view_details_btn = ttk.Button(grab_section, text="👁 详情", command=self._on_view_details, state="disabled", bootstyle="info")
self.view_details_btn.pack(side="left", padx=(0, 6))
# Interval setting
interval_section = ttk.Frame(action_row)
interval_section.pack(side="left")
ttk.Label(interval_section, text="间隔(s)").pack(side="left", padx=(0, 4))
self.interval_entry = ttk.Entry(interval_section, width=4, font=("Segoe UI", 10))
self.interval_entry.insert(0, "0.5")
self.interval_entry.pack(side="left")
self.count_label = ttk.Label(action_row, text="0 门", bootstyle="secondary")
self.count_label.pack(side="right")
# ========== LOG SECTION ==========
log_outer, log_card = self._create_card(bottom_frame, "📝 运行日志")
log_outer.pack(fill="both", expand=True)
self.log_text = tk.Text(
log_card,
height=8,
font=("JetBrains Mono", 9),
relief="flat",
padx=10,
pady=8,
wrap="word"
)
self.log_text.tag_configure("timestamp", foreground="gray")
self.log_text.tag_configure("info", foreground="white")
self.log_text.tag_configure("success", foreground="#3fb950")
self.log_text.tag_configure("warning", foreground="#d29922")
self.log_text.tag_configure("error", foreground="#f85149")
log_scrollbar = ttk.Scrollbar(log_card, orient="vertical", command=self.log_text.yview)
self.log_text.configure(yscrollcommand=log_scrollbar.set, state="disabled")
self.log_text.pack(side="left", fill="both", expand=True)
log_scrollbar.pack(side="right", fill="y")
def _log(self, message: str, level: str = "info"):
"""Append message to log area with color coding."""
timestamp = time.strftime("%H:%M:%S")
self.log_text.configure(state="normal")
# Insert timestamp
self.log_text.insert("end", f"[{timestamp}] ", "timestamp")
# Determine log level from message content if not specified
if level == "info":
if "✅" in message or "成功" in message or "🎉" in message:
level = "success"
elif "警告" in message or "⚠" in message:
level = "warning"
elif "错误" in message or "失败" in message or "❌" in message or "🛑" in message:
level = "error"
# Insert message with appropriate tag
self.log_text.insert("end", f"{message}\n", level)
self.log_text.see("end")
self.log_text.configure(state="disabled")
def _update_status(self, text: str, status: str = "default"):
"""Update status indicator."""
colors = {
"default": "gray",
"loading": "#d29922",
"success": "#3fb950",
"error": "#f85149"
}
color = colors.get(status, "gray")
self.status_dot.delete("all")
self.status_dot.create_oval(2, 2, 10, 10, fill=color, outline="")
self.status_label.configure(text=text)
bootstyle_map = {
"default": "secondary",
"loading": "warning",
"success": "success",
"error": "danger"
}
self.status_label.configure(bootstyle=bootstyle_map.get(status, "secondary"))
def _load_accounts(self):
"""Load accounts from account manager and populate the dropdown."""
accounts = self.account_manager.get_all_accounts()
if accounts:
account_names = [f"{acc.name} ({acc.username})" for acc in accounts]
self.account_combobox['values'] = account_names
# Select default account
default = self.account_manager.get_default_account()
if default:
for i, acc in enumerate(accounts):
if acc.id == default.id:
self.account_combobox.current(i)
self.current_account = acc
break
self._log(f"📂 已加载 {len(accounts)} 个账号")
else:
self._log("ℹ️ 尚未添加账号,请点击'添加'按钮添加账号")
def _on_account_selected(self, event=None):
"""Handle account selection change."""
idx = self.account_combobox.current()
accounts = self.account_manager.get_all_accounts()
if 0 <= idx < len(accounts):
self.current_account = accounts[idx]
self.account_manager.set_default_account(self.current_account.id)
# Check if this account has an active session
api = self.task_manager.get_api_session(self.current_account.id)
if api and hasattr(api, 'student_info') and api.student_info:
self._update_status(f"已登录: {self.current_account.name}", "success")
self._log(f"📌 已选择账号: {self.current_account.name} (已登录)")
self._enable_course_buttons()
# Load tabs from existing session
self._load_tabs_from_session(api)
else:
self._update_status("未登录", "default")
self._log(f"📌 已选择账号: {self.current_account.name}")
self._disable_course_buttons()
def _on_add_account(self):
"""Show dialog to add a new account."""
dialog = AccountDialog(self.root, "添加账号")
if dialog.result:
name, username, password = dialog.result
account = self.account_manager.add_account(name, username, password)
self._load_accounts()
# Select the new account
accounts = self.account_manager.get_all_accounts()
for i, acc in enumerate(accounts):
if acc.id == account.id:
self.account_combobox.current(i)
self.current_account = acc
break
self._log(f"✅ 已添加账号: {name}", "success")
def _on_edit_account(self):
"""Show dialog to edit the selected account."""
if not self.current_account:
messagebox.showwarning("警告", "请先选择一个账号")
return
dialog = AccountDialog(
self.root,
"编辑账号",
name=self.current_account.name,
username=self.current_account.username,
password=self.current_account.password
)
if dialog.result:
name, username, password = dialog.result
self.account_manager.update_account(
self.current_account.id,
name=name,
username=username,
password=password
)
self._load_accounts()
self._log(f"✅ 已更新账号: {name}", "success")
def _on_delete_account(self):
"""Delete the selected account."""
if not self.current_account:
messagebox.showwarning("警告", "请先选择一个账号")
return
confirm = messagebox.askyesno(
"确认删除",
f"确定要删除账号 '{self.current_account.name}' 吗?\n\n相关的抢课任务不会被自动删除。"
)
if confirm:
name = self.current_account.name
self.account_manager.remove_account(self.current_account.id)
self.current_account = None
self._load_accounts()
self._log(f"🗑 已删除账号: {name}")
def _on_about(self):
"""Show about dialog with project information."""
dialog = ttk.Toplevel(self.root)
dialog.title("关于")
dialog.geometry("480x450")
dialog.transient(self.root)
dialog.grab_set()
dialog.resizable(False, False)
# Center the dialog
dialog.update_idletasks()
x = self.root.winfo_x() + (self.root.winfo_width() - 480) // 2
y = self.root.winfo_y() + (self.root.winfo_height() - 450) // 2
dialog.geometry(f"480x450+{x}+{y}")
# Container
container = ttk.Frame(dialog)
container.pack(fill="both", expand=True, padx=30, pady=25)
# App icon and name
title_frame = ttk.Frame(container)
title_frame.pack(fill="x", pady=(0, 15))
app_icon = ttk.Label(
title_frame,
text="🎓",
font=("Segoe UI", 36)
)
app_icon.pack()
app_name_label = ttk.Label(
title_frame,
text=APP_NAME,
font=("Segoe UI", 18, "bold"),
bootstyle="primary"
)
app_name_label.pack(pady=(5, 0))
version_label = ttk.Label(
title_frame,
text=APP_VERSION,
font=("Segoe UI", 11),
bootstyle="secondary"
)
version_label.pack()
# Separator
ttk.Separator(container, orient="horizontal").pack(fill="x", pady=15)
# Description
desc_label = ttk.Label(
container,
text="一款基于 Python 的正方教务系统自动化选课工具",
font=("Segoe UI", 10),
wraplength=380,
justify="center"
)
desc_label.pack(pady=(0, 5))
features_label = ttk.Label(
container,
text="支持多账号管理、自动抢课、课程退选等功能",
font=("Segoe UI", 9),
bootstyle="secondary",
wraplength=380,
justify="center"
)
features_label.pack(pady=(0, 15))
# GitHub link
github_url = "https://github.com/vancehuds/VanceCoursePro"
github_frame = ttk.Frame(container)
github_frame.pack(pady=(0, 10))
github_icon = ttk.Label(
github_frame,
text="📦 开源地址:",
font=("Segoe UI", 10)
)
github_icon.pack(side="left")
github_link = ttk.Label(
github_frame,
text=github_url,
font=("Segoe UI", 10, "underline"),
bootstyle="info",
cursor="hand2"
)
github_link.pack(side="left", padx=(5, 0))
github_link.bind("<Button-1>", lambda e: webbrowser.open(github_url))
# Copyright
copyright_label = ttk.Label(
container,
text="© 2025 VanceCoursePro Contributors",
font=("Segoe UI", 9),
bootstyle="secondary"
)
copyright_label.pack(pady=(15, 0))
license_label = ttk.Label(
container,
text="MIT License",
font=("Segoe UI", 9),
bootstyle="secondary"
)
license_label.pack()
# Close button
ttk.Button(
container,
text="关闭",
command=dialog.destroy,
bootstyle="secondary",
width=10
).pack(pady=(20, 0))
def _on_settings(self):
"""Show settings dialog to configure base URL."""
dialog = ttk.Toplevel(self.root)
dialog.title("设置")
dialog.geometry("500x260")
dialog.transient(self.root)
dialog.grab_set()
# Center the dialog
dialog.update_idletasks()
x = self.root.winfo_x() + (self.root.winfo_width() - 500) // 2
y = self.root.winfo_y() + (self.root.winfo_height() - 200) // 2
dialog.geometry(f"500x260+{x}+{y}")
# Container
container = ttk.Frame(dialog)
container.pack(fill="both", expand=True, padx=20, pady=20)
# Header
header = ttk.Label(
container,
text="⚙️ 应用设置",
font=("Segoe UI", 12, "bold"),
bootstyle="primary"
)
header.pack(anchor="w", pady=(0, 15))
# Base URL row
url_frame = ttk.Frame(container)
url_frame.pack(fill="x", pady=(0, 10))
ttk.Label(url_frame, text="服务器地址:", width=10).pack(side="left")
url_entry = ttk.Entry(url_frame, width=50, font=("Segoe UI", 10))
url_entry.pack(side="left", fill="x", expand=True)
url_entry.insert(0, self.account_manager.get_base_url())
# Hint label
hint = ttk.Label(
container,
text="提示:修改后需要重新登录才能生效",
bootstyle="secondary",
font=("Segoe UI", 9)
)
hint.pack(anchor="w", pady=(0, 15))
def on_save():
new_url = url_entry.get().strip()
if new_url:
self.account_manager.set_base_url(new_url)
self._log(f"✅ 服务器地址已更新为: {new_url}", "success")
messagebox.showinfo("成功", "服务器地址已保存,请重新登录以使用新地址。", parent=dialog)
else:
self.account_manager.set_base_url(self.account_manager.DEFAULT_BASE_URL)
self._log(f"✅ 服务器地址已重置为默认值", "success")
dialog.destroy()
def on_reset():
url_entry.delete(0, "end")
url_entry.insert(0, self.account_manager.DEFAULT_BASE_URL)
# Buttons
btn_frame = ttk.Frame(container)
btn_frame.pack(fill="x")
ttk.Button(
btn_frame,
text="取消",
command=dialog.destroy,
bootstyle="secondary"
).pack(side="right", padx=(8, 0))
ttk.Button(
btn_frame,
text="保存",
command=on_save,
bootstyle="success"
).pack(side="right")
ttk.Button(
btn_frame,
text="重置默认",
command=on_reset,
bootstyle="warning-outline"
).pack(side="left")
def _on_login(self):
"""Handle login button click for the selected account."""
if not self.current_account:
self._log("⚠ 警告: 请先选择或添加一个账号。", "warning")
return
username = self.current_account.username
password = self.current_account.password
if not username or not password:
self._log("⚠ 警告: 账号信息不完整。", "warning")
return
self.login_btn.configure(state="disabled")
self._update_status("登录中...", "loading")
self._log(f"🔄 正在登录: {self.current_account.name} ({username})...")
account_id = self.current_account.id
def do_login():
try:
base_url = self.account_manager.get_base_url()
api = JwglxtAPI(base_url=base_url) # Create new session with configured base URL
api.login(username, password)
api.init_course_selection()
# Store session in task manager (bound to account)
self.task_manager.set_api_session(account_id, api)
self.root.after(0, lambda: self._on_login_success())
except Exception as e:
error_msg = str(e)
self.root.after(0, lambda err=error_msg: self._on_login_fail(err))
threading.Thread(target=do_login, daemon=True).start()
@property
def api(self) -> JwglxtAPI:
"""Get the API session for the current account."""
if self.current_account:
api = self.task_manager.get_api_session(self.current_account.id)
if api:
return api
# Return a dummy API if no session exists (will fail gracefully)
return JwglxtAPI(base_url=self.account_manager.get_base_url())
def _enable_course_buttons(self):
"""Enable course-related buttons."""
self.load_courses_btn.configure(state="normal")
self.load_all_btn.configure(state="normal")
self.load_all_details_btn.configure(state="normal")
self.load_details_only_btn.configure(state="disabled")
self.load_more_btn.configure(state="disabled")
def _disable_course_buttons(self):
"""Disable course-related buttons."""
self.load_courses_btn.configure(state="disabled")
self.load_all_btn.configure(state="disabled")
self.load_all_details_btn.configure(state="disabled")
self.load_details_only_btn.configure(state="disabled")
self.load_more_btn.configure(state="disabled")
def _load_tabs_from_session(self, api: JwglxtAPI):
"""Load tabs from an existing API session."""
tabs = api.student_info.get('tabs', [])
if tabs:
tab_names = [t['name'] for t in tabs]
self.tab_combobox['values'] = tab_names
if tab_names:
self.tab_combobox.current(0)
def _on_login_success(self):
"""Update UI after successful login."""
self._update_status(f"已登录: {self.current_account.name}", "success")
self.login_btn.configure(state="normal")
self._enable_course_buttons()
self._log("✅ 登录成功!", "success")
api = self.task_manager.get_api_session(self.current_account.id)
if api:
self._log(f"📋 学生信息: njdm_id={api.student_info.get('njdm_id')}, zyh_id={api.student_info.get('zyh_id')}")
self._load_tabs_from_session(api)
tabs = api.student_info.get('tabs', [])
if tabs:
self._log(f"📑 获取到课程类型: {[t['name'] for t in tabs]}")
else:
self._log("⚠ 未获取到课程类型选项", "warning")
def _on_login_fail(self, error: str):
"""Update UI after failed login."""
self._update_status("登录失败", "error")
self.login_btn.configure(state="normal")
self._log(f"❌ 登录失败: {error}", "error")
def _on_load_courses(self):
"""Handle load courses button click."""
self.load_courses_btn.configure(state="disabled")
filter_name = self.search_entry.get().strip()
# Determine selected tab
selected_name = self.tab_combobox.get()
selected_tab = None
for t in self.api.student_info.get('tabs', []):
if t['name'] == selected_name:
selected_tab = t
break
if selected_tab:
self.api.student_info['kklxdm'] = selected_tab['kklxdm']
self.api.student_info['xkkz_id'] = selected_tab['xkkz_id']
if 'rwlx' in selected_tab:
self.api.student_info['rwlx'] = selected_tab['rwlx']
self._log(f"📂 切换至: {selected_name}")
self._log(f"🔄 正在加载课程列表..." + (f" (搜索: {filter_name})" if filter_name else ""))
self.current_page = 1
def do_load():
try:
courses = self.api.get_course_list(filter_name=filter_name if filter_name else None, page=1)
self.root.after(0, lambda: self._update_course_list(courses, clear=True))
except Exception as e:
error_msg = str(e)
self.root.after(0, lambda err=error_msg: self._on_load_fail(err))
threading.Thread(target=do_load, daemon=True).start()
def _update_course_list(self, courses: list, clear: bool = True):
"""Update treeview with course data."""
if clear:
self.course_tree.delete(*self.course_tree.get_children())
self.courses = []
self.courses.extend(courses)
for c in courses:
# Check if course is already selected based on xxkbj field
selected_status = "★" if c.get("xxkbj") == "1" else ""
self.course_tree.insert("", "end", values=(
c.get("kch_id", ""),
c.get("kcmc", ""),
c.get("xf", ""),
selected_status,
"",
"",
"",
))
self.load_courses_btn.configure(state="normal")
if courses:
self.load_more_btn.configure(state="normal")
else:
self.load_more_btn.configure(state="disabled")
if not clear:
self._log("📭 没有更多课程了。")
if self.courses:
self.load_details_only_btn.configure(state="normal")
else:
self.load_details_only_btn.configure(state="disabled")
# Update count label
self.count_label.configure(text=f"共 {len(self.courses)} 门课程")
self._log(f"✅ 加载完成,本次 {len(courses)} 门,总共 {len(self.courses)} 门。", "success")
def _on_load_more_courses(self):
"""Handle load more courses button click."""
self.load_more_btn.configure(state="disabled")
self.current_page += 1
filter_name = self.search_entry.get().strip()
self._log(f"🔄 正在加载第 {self.current_page} 页...")
def do_load_more():