Repository navigation
Expand file tree
/
Copy pathAppGUI_CHS.py
More file actions
1870 lines (1642 loc) · 84.1 KB
/
Copy pathAppGUI_CHS.py
File metadata and controls
1870 lines (1642 loc) · 84.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Author: Hydrooxygen
# Github: github.com/Hydrooxzgen
# ------------------------------------------------------------
"""
App_GUI v1.0.0 Single Language Version
此为单语言版本不再更新
"""
import hashlib
import os
import random
import shutil
import socket
import subprocess
import sys
import threading
# ------------------------------------------------------------
# 提醒:
# 必须在 import tkinter 之前设置 TCL_LIBRARY / TK_LIBRARY绑定输入
# ------------------------------------------------------------
def _fix_tcl_library():
if os.environ.get("TCL_LIBRARY") and os.environ.get("TK_LIBRARY"):
return
candidates = [sys.prefix, os.path.dirname(sys.executable)]
if hasattr(sys, "base_prefix") and sys.base_prefix not in candidates:
candidates.append(sys.base_prefix)
for base in candidates:
tcl_dir = os.path.join(base, "tcl", "tcl8.6")
tk_dir = os.path.join(base, "tcl", "tk8.6")
if os.path.isfile(os.path.join(tcl_dir, "init.tcl")):
os.environ.setdefault("TCL_LIBRARY", tcl_dir)
if os.path.isdir(tk_dir):
os.environ.setdefault("TK_LIBRARY", tk_dir)
if os.environ.get("TCL_LIBRARY") and os.environ.get("TK_LIBRARY"):
return
_fix_tcl_library()
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox, scrolledtext, simpledialog, ttk
try:
import requests
except ImportError:
requests = None
try:
from pythonping import ping as py_ping
except ImportError:
py_ping = None
APP_SHORT_NAME = "NiceProgram" # shorname for 侧边栏
APP_TITLE = "NiceProgram App" # fullname for title & about page
APP_VERSION = "1.0.0 单语言简体中文版-不再更新" # version here
APP_AUTHOR = "Hydrooxygen" # Author: Hydrooxygen
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
USERFILES_DIR = os.path.join(BASE_DIR, "UserFiles")
TEMPLATE_DIR = os.path.join(USERFILES_DIR, "template")
MORSE_CODES = {
"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".",
"f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---",
"k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---",
"p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-",
"u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--",
"z": "--..",
}
# **颜色主题**
COLORS = {
"bg": "#F1F5F9",
"sidebar": "#1E293B",
"sidebar_text": "#E2E8F0",
"sidebar_sel": "#2563EB",
"card": "#FFFFFF",
"primary": "#2563EB",
"primary_dark": "#1D4ED8",
"success": "#16A34A",
"danger": "#DC2626",
"warning": "#D97706",
"text": "#0F172A",
"text_light": "#64748B",
"border": "#E2E8F0",
"console": "#0B1220",
"console_text": "#E2E8F0",
"statusbar": "#0F172A",
}
FONT = "Microsoft YaHei UI"
MONO = "Consolas"
def md5_hex(text: str) -> str:
"""返回字符串的md5十六进制"""
return hashlib.md5(text.encode("utf-8")).hexdigest()
def has_chinese(text: str) -> bool:
return any("\u4e00" <= ch <= "\u9fff" for ch in text)
def ensure_user_dirs(username: str) -> None:
"""!!creat template dirs for new user!!"""
user_dir = os.path.join(USERFILES_DIR, username)
os.makedirs(user_dir, exist_ok=True)
for sub in ("GuessFist", "GuessNumbers", "BMI"):
dst = os.path.join(user_dir, sub)
os.makedirs(dst, exist_ok=True)
src = os.path.join(TEMPLATE_DIR, sub)
if os.path.isdir(src):
for name in os.listdir(src):
src_file = os.path.join(src, name)
if os.path.isfile(src_file):
shutil.copy2(src_file, dst)
# ============================================================
# 登录 / 注册 enter box
# ============================================================
class LoginDialog(tk.Toplevel):
RESULT_CANCEL = 0
RESULT_GUEST = 1
RESULT_OK = 2
def __init__(self, master):
super().__init__(master)
self.title("登录")
self.configure(bg=COLORS["bg"])
self.resizable(False, False)
self.transient(master)
self.result = LoginDialog.RESULT_CANCEL
self.username_var = tk.StringVar()
self.password_var = tk.StringVar()
self._build()
self._center(master)
self.grab_set()
self.entry_user.focus_set()
self.bind("<Return>", lambda e: self.do_login())
def _center(self, master):
self.update_idletasks()
w, h = self.winfo_width(), self.winfo_height()
x = master.winfo_rootx() + (master.winfo_width() - w) // 2
y = master.winfo_rooty() + (master.winfo_height() - h) // 2
self.geometry(f"+{max(x, 0)}+{max(y, 0)}")
def _build(self):
outer = tk.Frame(self, bg=COLORS["bg"], padx=36, pady=28)
outer.pack(fill="both", expand=True)
tk.Label(outer, text="👋 欢迎使用", font=(FONT, 18, "bold"),
bg=COLORS["bg"], fg=COLORS["text"]).pack(anchor="w")
tk.Label(outer, text=APP_TITLE, font=(FONT, 10),
bg=COLORS["bg"], fg=COLORS["text_light"]).pack(anchor="w", pady=(2, 18))
tk.Label(outer, text="用户名", font=(FONT, 10), bg=COLORS["bg"],
fg=COLORS["text_light"]).pack(anchor="w")
self.entry_user = self._mk_entry(outer, textvariable=self.username_var)
self.entry_user.pack(fill="x", pady=(4, 12), ipady=4)
tk.Label(outer, text="密码", font=(FONT, 10), bg=COLORS["bg"],
fg=COLORS["text_light"]).pack(anchor="w")
self.entry_pwd = self._mk_entry(outer, show="•", textvariable=self.password_var)
self.entry_pwd.pack(fill="x", pady=(4, 18), ipady=4)
btns = tk.Frame(outer, bg=COLORS["bg"])
btns.pack(fill="x")
self._mk_btn(btns, "登 录", self.do_login, "primary").pack(side="left", fill="x", expand=True)
self._mk_btn(btns, "注 册", self.do_signup, "ghost").pack(side="left", padx=(10, 0), fill="x", expand=True)
self._mk_btn(outer, "以游客身份进入", lambda: self._finish(LoginDialog.RESULT_GUEST),
"ghost").pack(fill="x", pady=(10, 0))
def _mk_entry(self, parent, show=None, textvariable=None):
return tk.Entry(parent, show=show, textvariable=textvariable, font=(FONT, 12),
relief="solid", bd=1,
highlightthickness=1,
highlightbackground=COLORS["border"],
highlightcolor=COLORS["primary"],
bg="white", fg=COLORS["text"])
def _mk_btn(self, parent, text, cmd, kind="primary"):
cfg = {
"primary": (COLORS["primary"], "white", COLORS["primary_dark"]),
"ghost": (COLORS["card"], COLORS["text"], COLORS["border"]),
}[kind]
return tk.Button(parent, text=text, command=cmd, bg=cfg[0], fg=cfg[1],
activebackground=cfg[2], activeforeground=cfg[1],
font=(FONT, 10, "bold"), relief="flat", bd=0,
cursor="hand2", padx=12, pady=7)
def _finish(self, result):
self.result = result
self.destroy()
def do_login(self):
name = self.username_var.get().strip()
pwd = self.password_var.get()
if not name or not pwd:
messagebox.showerror("错误", "请输入用户名和密码!", parent=self)
return
user_dir = os.path.join(USERFILES_DIR, name)
pwd_file = os.path.join(user_dir, "password.txt")
if not os.path.isdir(user_dir):
messagebox.showerror("未知用户", f"用户名 {name} 不存在!", parent=self)
return
if not os.path.isfile(pwd_file):
reset = messagebox.askyesno(
"密码文件丢失",
"注意:你的密码文件丢失了,需要重新设置密码,你的用户数据将会丢失。确定吗?",
parent=self)
if not reset:
return
ensure_user_dirs(name)
new_pwd = simpledialog.askstring("新密码", "输入新密码:", parent=self, show="•")
if not new_pwd:
return
with open(pwd_file, "w", encoding="utf-8") as f:
f.write(md5_hex(new_pwd))
messagebox.showinfo("成功", "密码已重置,请重新登录!", parent=self)
return
with open(pwd_file, "r", encoding="utf-8") as f:
stored = f.read().strip()
if md5_hex(pwd) == stored:
self.master.login_success(name)
self._finish(LoginDialog.RESULT_OK)
else:
messagebox.showerror("密码错误", "密码错误,请重试!", parent=self)
def do_signup(self):
name = self.username_var.get().strip()
pwd = self.password_var.get()
if not name or not pwd:
messagebox.showerror("错误", "请输入用户名和密码!", parent=self)
return
user_dir = os.path.join(USERFILES_DIR, name)
if os.path.isdir(user_dir):
messagebox.showerror("用户名存在", "用户名已经存在了!", parent=self)
return
os.makedirs(user_dir, exist_ok=True)
with open(os.path.join(user_dir, "password.txt"), "w", encoding="utf-8") as f:
f.write(md5_hex(pwd))
ensure_user_dirs(name)
messagebox.showinfo("注册成功", "注册成功,请重新登录!", parent=self)
self.entry_pwd.delete(0, "end")
# ============================================================
# Main App
# ============================================================
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title(f"{APP_TITLE} V{APP_VERSION}")
self.geometry("1150x740")
self.minsize(980, 640)
self.configure(bg=COLORS["bg"])
# ---- login status(启动时为游客,登录后通过 login_success() 切换)----
self.logged = False
self.username = "游客"
self.userpath = None
self.userpath_win = None
# ---- 各个功能的temp status ----
self.game = {}
self._setup_style()
self._build_layout()
self._register_pages()
self.show_page("home")
self.after(300, self.open_login)
# --------------------------------------------------------
# 样式&布局
# --------------------------------------------------------
def _setup_style(self):
self.option_add("*Font", (FONT, 10))
style = ttk.Style(self)
style.theme_use("clam")
style.configure("Nav.Treeview",
background=COLORS["sidebar"],
fieldbackground=COLORS["sidebar"],
foreground=COLORS["sidebar_text"],
borderwidth=0,
rowheight=32,
font=(FONT, 10))
style.map("Nav.Treeview",
background=[("selected", COLORS["sidebar_sel"])],
foreground=[("selected", "white")])
style.configure("TCombobox", fieldbackground="white")
def _build_layout(self):
# ---- side bar ----
self.sidebar = tk.Frame(self, bg=COLORS["sidebar"], width=230)
self.sidebar.pack(side="left", fill="y")
self.sidebar.pack_propagate(False)
logo = tk.Frame(self.sidebar, bg=COLORS["sidebar"])
logo.pack(fill="x", pady=(22, 12))
tk.Label(logo, text=APP_SHORT_NAME, font=(FONT, 15, "bold"),
bg=COLORS["sidebar"], fg="white").pack()
tk.Label(logo, text=f"VERSION {APP_VERSION}", font=(FONT, 9),
bg=COLORS["sidebar"], fg="#94A3B8").pack()
self.nav = ttk.Treeview(self.sidebar, show="tree", style="Nav.Treeview")
self.nav.pack(fill="both", expand=True, padx=8, pady=(4, 8))
self.nav.bind("<<TreeviewSelect>>", self._on_nav_select)
# ---- 内容区域(右侧) ----
right = tk.Frame(self, bg=COLORS["bg"])
right.pack(side="left", fill="both", expand=True)
self.content = tk.Frame(right, bg=COLORS["bg"])
self.content.pack(fill="both", expand=True)
self._build_statusbar(right)
def _build_statusbar(self, parent):
bar = tk.Frame(parent, bg=COLORS["statusbar"], height=36)
bar.pack(fill="x", side="bottom")
bar.pack_propagate(False)
self.status_user = tk.Label(bar, text="👤 当前用户:游客", bg=COLORS["statusbar"],
fg="#E2E8F0", font=(FONT, 9))
self.status_user.pack(side="left", padx=14)
self.btn_switch = tk.Button(bar, text="登录 / 切换账户", command=self.open_login,
bg=COLORS["statusbar"], fg="#93C5FD",
activebackground=COLORS["statusbar"],
activeforeground="white", bd=0, relief="flat",
cursor="hand2", font=(FONT, 9))
self.btn_switch.pack(side="right", padx=(0, 8))
self.btn_logout = tk.Button(bar, text="退出登录", command=self.logout,
bg=COLORS["statusbar"], fg="#FCA5A5",
activebackground=COLORS["statusbar"],
activeforeground="white", bd=0, relief="flat",
cursor="hand2", font=(FONT, 9))
self.btn_logout.pack(side="right", padx=8)
self.btn_logout.pack_forget()
# --------------------------------------------------------
# 页面注册&切换逻辑
# --------------------------------------------------------
#注册不同类别
NAV_GROUPS = [
("首页", [("home", " 首页")]),
("游戏娱乐", [("guess", " 猜数字"), ("fist", " 石头剪刀布"), ("mind", " 读心术")]),
("数学工具", [("base", " 进制转换"), ("accuracy", " 计算正确率"),
("average", " 计算平均数"), ("rabbit", " 鸡兔同笼"),
("collatz", " Collatz数列"), ("table", " 九九乘法表"),
("bmi", " BMI检测"), ("money", " 凑钱数"),
("sort", " 按升/降排序数列")]),
("网络工具", [("translate", " 中英互译机"), ("ping", " Ping")]),
("文本工具", [("morse", " 摩斯密码转换器"), ("talk", " Talk out")]),
("系统工具", [("shutdown", " 定时关机"), ("batch", " 批量创建文件"),
("activate", " 激活Windows"), ("bsod", " 让你的设备蓝屏"),
("prank", " 恶搞")]),
("账户", [("account", " 账户相关")]),
("其他", [("feedback", " 反馈问题"), ("changelog", " 更新日志"),
("about", " 关于")]),
]
PAGE_BUILDERS = {
"home": "_build_home_page",
"guess": "_build_guess_page",
"fist": "_build_fist_page",
"mind": "_build_mind_page",
"base": "_build_base_page",
"accuracy": "_build_accuracy_page",
"average": "_build_average_page",
"rabbit": "_build_rabbit_page",
"collatz": "_build_collatz_page",
"table": "_build_table_page",
"bmi": "_build_bmi_page",
"money": "_build_money_page",
"sort": "_build_sort_page",
"translate": "_build_translate_page",
"ping": "_build_ping_page",
"morse": "_build_morse_page",
"talk": "_build_talk_page",
"shutdown": "_build_shutdown_page",
"batch": "_build_batch_page",
"activate": "_build_activate_page",
"bsod": "_build_bsod_page",
"prank": "_build_prank_page",
"account": "_build_account_page",
"feedback": "_build_feedback_page",
"changelog": "_build_changelog_page",
"about": "_build_about_page",
}
def _register_pages(self):
self.page_frames = {}
self.page_builders = {}
for pid, builder in self.PAGE_BUILDERS.items():
self.page_builders[pid] = getattr(self, builder)
for group, items in self.NAV_GROUPS:
gid = self.nav.insert("", "end", text=group, open=True)
for pid, label in items:
self.nav.insert(gid, "end", iid=pid, text=label)
def _on_nav_select(self, _event):
sel = self.nav.selection()
if sel and sel[0] in self.page_builders:
self.show_page(sel[0])
def show_page(self, pid):
if pid not in self.page_frames:
frame = tk.Frame(self.content, bg=COLORS["bg"])
frame.place(relx=0, rely=0, relwidth=1, relheight=1)
self.page_builders[pid](frame)
self.page_frames[pid] = frame
for f in self.page_frames.values():
f.tkraise()
self.page_frames[pid].tkraise()
# --------------------------------------------------------
# global控件
# --------------------------------------------------------
def _card(self, parent, title, subtitle=""):
card = tk.Frame(parent, bg=COLORS["card"],
highlightbackground=COLORS["border"], highlightthickness=1)
tk.Label(card, text=title, font=(FONT, 12, "bold"),
bg=COLORS["card"], fg=COLORS["text"]).pack(anchor="w", padx=16, pady=(12, 2))
if subtitle:
tk.Label(card, text=subtitle, font=(FONT, 9),
bg=COLORS["card"], fg=COLORS["text_light"]).pack(anchor="w", padx=16)
body = tk.Frame(card, bg=COLORS["card"])
body.pack(fill="both", expand=True, padx=16, pady=(6, 14))
return card, body
def _header(self, parent, title, subtitle=""):
header = tk.Frame(parent, bg=COLORS["bg"])
header.pack(fill="x", padx=24, pady=(20, 10))
tk.Label(header, text=title, font=(FONT, 17, "bold"),
bg=COLORS["bg"], fg=COLORS["text"]).pack(anchor="w")
if subtitle:
tk.Label(header, text=subtitle, font=(FONT, 9),
bg=COLORS["bg"], fg=COLORS["text_light"]).pack(anchor="w")
def _mk_entry(self, parent, width=26, show=None, textvariable=None):
return tk.Entry(parent, width=width, show=show, textvariable=textvariable,
font=(FONT, 11), relief="solid", bd=1,
highlightthickness=1,
highlightbackground=COLORS["border"],
highlightcolor=COLORS["primary"],
bg="white", fg=COLORS["text"])
def _mk_btn(self, parent, text, cmd, kind="primary", width=None):
cfg = {
"primary": (COLORS["primary"], "white", COLORS["primary_dark"]),
"success": (COLORS["success"], "white", "#15803D"),
"danger": (COLORS["danger"], "white", "#B91C1C"),
"warning": (COLORS["warning"], "white", "#B45309"),
"ghost": (COLORS["card"], COLORS["text"], COLORS["border"]),
}[kind]
return tk.Button(parent, text=text, command=cmd, bg=cfg[0], fg=cfg[1],
activebackground=cfg[2], activeforeground=cfg[1],
font=(FONT, 10, "bold"), relief="flat", bd=0,
cursor="hand2", padx=14, pady=7, width=width)
def _mk_text(self, parent, height=10, width=None, state="normal"):
return tk.Text(parent, height=height, width=width, font=(MONO, 10),
bg=COLORS["console"], fg=COLORS["console_text"],
relief="flat", bd=0, wrap="word",
highlightbackground=COLORS["border"], highlightthickness=1,
insertbackground="white", state=state)
def _row(self, parent, label_text, factory, *args, padx=0, **kwargs):
"""创建一行"标签 + 输入控件"。
factory 在 row 容器内创建控件(master 直接就是 row),
避免 pack(in_=...) 的 reparent 导致输入框消失/错位。!!!重要,警惕!!!
返回 (row, widget),row 可用于整行显示/隐藏。
"""
row = tk.Frame(parent, bg=COLORS["card"])
row.pack(fill="x", pady=4)
if label_text:
tk.Label(row, text=label_text, font=(FONT, 10), bg=COLORS["card"],
fg=COLORS["text"], width=14, anchor="w").pack(side="left")
widget = factory(row, *args, **kwargs)
widget.pack(side="left", padx=padx)
return row, widget
def _mk_spinbox(self, parent, from_, to, width=16):
return tk.Spinbox(parent, from_=from_, to=to, font=(FONT, 11), width=width)
@staticmethod
def _set_text(widget, text):
widget.configure(state="normal")
widget.delete("1.0", "end")
widget.insert("1.0", text)
widget.configure(state="disabled")
@staticmethod
def _append_text(widget, text):
widget.configure(state="normal")
widget.insert("end", text)
widget.see("end")
widget.configure(state="disabled")
# --------------------------------------------------------
# 登录 / 账户
# --------------------------------------------------------
def open_login(self):
dialog = LoginDialog(self)
self.wait_window(dialog)
def login_success(self, username):
self.username = username
self.userpath = os.path.join(USERFILES_DIR, username)
self.userpath_win = self.userpath
self.logged = True
self._update_statusbar()
if "account" in self.page_frames:
self._rebuild_account_page()
def logout(self):
self.logged = False
self.username = "游客"
self.userpath = None
self.userpath_win = None
self._update_statusbar()
if "account" in self.page_frames:
self._rebuild_account_page()
messagebox.showinfo("已退出", "你已退出登录,当前为游客身份。")
def _update_statusbar(self):
self.status_user.config(text=f"👤 当前用户:{self.username}" +
("(已登录)" if self.logged else "(游客)"))
if self.logged:
self.btn_logout.pack(side="right", padx=8)
else:
self.btn_logout.pack_forget()
# 同步更新主页上的账户状态卡片与欢迎语
if getattr(self, "home_stat_user", None) and self.home_stat_user.winfo_exists():
self.home_stat_user.config(
text="已登录" if self.logged else "游客",
fg=COLORS["success"] if self.logged else COLORS["warning"])
if getattr(self, "home_hero_user", None) and self.home_hero_user.winfo_exists():
self.home_hero_user.config(
text=f"VERSION {APP_VERSION} · 当前用户:{self.username}")
def _rebuild_account_page(self):
pid = "account"
if pid in self.page_frames:
self.page_frames[pid].destroy()
del self.page_frames[pid]
if pid in self.game:
del self.game[pid]
self.show_page(pid)
# --------------------------------------------------------
# Main Page
# --------------------------------------------------------
def _build_home_page(self, frame):
self._header(frame, "首页", f"欢迎使用 {APP_TITLE}")
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
hero = tk.Frame(wrap, bg=COLORS["primary"], padx=28, pady=24)
hero.pack(fill="x")
tk.Label(hero, text=f"欢迎来到 {APP_TITLE}", font=(FONT, 20, "bold"),
bg=COLORS["primary"], fg="white").pack(anchor="w")
self.home_hero_user = tk.Label(hero, text=f"VERSION {APP_VERSION} · 当前用户:{self.username}",
font=(FONT, 11), bg=COLORS["primary"], fg="#DBEAFE")
self.home_hero_user.pack(anchor="w", pady=(6, 0))
cards_row = tk.Frame(wrap, bg=COLORS["bg"])
cards_row.pack(fill="x", pady=(16, 0))
def stat_card(title, value, color):
card = tk.Frame(cards_row, bg=COLORS["card"], highlightbackground=COLORS["border"],
highlightthickness=1)
card.pack(side="left", fill="x", expand=True, padx=(0, 12))
tk.Label(card, text=title, font=(FONT, 10), bg=COLORS["card"],
fg=COLORS["text_light"]).pack(anchor="w", padx=16, pady=(12, 2))
val = tk.Label(card, text=value, font=(FONT, 16, "bold"), bg=COLORS["card"],
fg=color)
val.pack(anchor="w", padx=16, pady=(0, 12))
return val
total = sum(len(items) for _, items in self.NAV_GROUPS)
stat_card("功能总数", f"{total}", COLORS["primary"])
self.home_stat_user = stat_card("账户状态", "已登录" if self.logged else "游客",
COLORS["success"] if self.logged else COLORS["warning"])
stat_card("数据目录", "UserFiles", COLORS["text_light"])
card, body = self._card(wrap, "快速开始", "从左侧导航选择一个功能开始使用")
tk.Label(body, text="· 🎯 猜数字 —— 与计算机斗智斗勇\n"
"· ✊ 石头剪刀布 —— 经典对决\n"
"· 🌐 中英互译机 —— 在线翻译\n"
"· 📶 Ping —— 网络连通性测试\n"
"· 更多功能尽在左侧导航…",
font=(FONT, 10), bg=COLORS["card"], fg=COLORS["text"],
justify="left").pack(anchor="w")
# --------------------------------------------------------
# 猜数字实现
# --------------------------------------------------------
def _build_guess_page(self, frame):
self._header(frame, "猜数字", "输入范围开始游戏,看看你能用多少次猜中")
self.game["guess"] = {"target": None, "tries": 0, "min": None, "max": None,
"history": []}
g = self.game["guess"]
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
left, left_body = self._card(wrap, "游戏设置")
left.pack(side="left", fill="y", padx=(0, 12))
left_body.config(width=300)
_, self.guess_min = self._row(left_body, "最小数", self._mk_entry, width=12)
_, self.guess_max = self._row(left_body, "最大数", self._mk_entry, width=12)
self._mk_btn(left_body, "开始新游戏", self.guess_start, "success").pack(fill="x", pady=(10, 4))
self.guess_status = tk.Label(left_body, text="状态:等待开始", font=(FONT, 10),
bg=COLORS["card"], fg=COLORS["text_light"], anchor="w")
self.guess_status.pack(fill="x", pady=(8, 0))
tk.Label(left_body, text="提示:输入 exit 退出本轮,输入 empty 清空历史记录",
font=(FONT, 9), bg=COLORS["card"], fg=COLORS["text_light"],
wraplength=260, justify="left").pack(anchor="w", pady=(10, 0))
right, right_body = self._card(wrap, "猜测记录")
right.pack(side="left", fill="both", expand=True)
input_row = tk.Frame(right_body, bg=COLORS["card"])
input_row.pack(fill="x", pady=(0, 8))
self.guess_input = self._mk_entry(input_row, width=20)
self.guess_input.pack(side="left", ipady=3)
self._mk_btn(input_row, "猜", self.guess_submit, "primary").pack(side="left", padx=(8, 0))
self.guess_input.bind("<Return>", lambda e: self.guess_submit())
self.guess_log = self._mk_text(right_body, height=16)
self.guess_log.pack(fill="both", expand=True)
def guess_start(self):
g = self.game["guess"]
try:
low = int(self.guess_min.get().strip())
high = int(self.guess_max.get().strip())
except ValueError:
messagebox.showerror("数值错误", "请在左侧「最小数 / 最大数」输入框中填写整数(如 1 和 100)!")
self.guess_min.focus_set()
return
if low > high:
low, high = high, low
g.update(target=random.randint(low, high), tries=0, min=low, max=high,
history=[f"新游戏:范围 {low} ~ {high}"])
self.guess_status.config(text=f"状态:已开始,范围 {low} ~ {high}", fg=COLORS["success"])
self._set_text(self.guess_log, f"计算机已经创建了 {low}~{high} 中的数字,开始猜吧!\n")
self.guess_input.focus_set()
def guess_submit(self):
g = self.game["guess"]
if g["target"] is None:
messagebox.showinfo("提示", "请先点击「开始新游戏」!")
return
raw = self.guess_input.get().strip()
self.guess_input.delete(0, "end")
if raw.lower() == "exit":
self.guess_status.config(text="状态:已退出本轮", fg=COLORS["warning"])
self._append_text(self.guess_log, "已退出本轮。\n")
return
if raw.lower() == "empty":
if not self.logged:
messagebox.showerror("失败", "你暂未登录!此操作无效")
return
path = os.path.join(self.userpath, "GuessNumbers", "GuessNumbers.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("GuessNumber FREQUENCY")
messagebox.showinfo("成功", "清除成功!")
return
if not raw.isdecimal():
messagebox.showerror("数值错误", "你输入的不是数字")
return
n = int(raw)
if not (g["min"] <= n <= g["max"]):
messagebox.showerror("超出范围", "输入的数值超出范围!")
return
if n == g["target"]:
g["tries"] += 1
self._append_text(self.guess_log, f"🎉 猜对了!数字是 {g['target']},共用了 {g['tries']} 次。\n")
self.guess_status.config(text=f"状态:猜中!用时 {g['tries']} 次", fg=COLORS["success"])
if self.logged:
try:
with open(os.path.join(self.userpath, "GuessNumbers", "GuessNumbers.txt"),
"a", encoding="utf-8") as f:
f.write(f"""\n错误次数:{g['tries']}
正确数字:{g['target']}
日期:{datetime.today()}
范围:{g['min']}~{g['max']}
---------""")
except OSError as e:
messagebox.showerror("错误", f"写入记录失败:{e}")
g["target"] = None
elif n > g["target"]:
g["tries"] += 1
self._append_text(self.guess_log, f"第 {g['tries']} 次:{n} —— 猜大了!\n")
else:
g["tries"] += 1
self._append_text(self.guess_log, f"第 {g['tries']} 次:{n} —— 猜小了!\n")
# --------------------------------------------------------
# 石头剪刀布实现
# --------------------------------------------------------
def _build_fist_page(self, frame):
self._header(frame, "石头剪刀布", "与计算机来一场经典对决")
self.game["fist"] = {"win": 0, "lose": 0, "tie": 0, "last": ""}
f = self.game["fist"]
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
arena, arena_body = self._card(wrap, "对战区")
arena.pack(fill="x")
self.fist_last = tk.Label(arena_body, text="点击下方按钮出拳!", font=(FONT, 13),
bg=COLORS["card"], fg=COLORS["text"])
self.fist_last.pack(pady=8)
btn_row = tk.Frame(arena_body, bg=COLORS["card"])
btn_row.pack(pady=10)
for text, kind in (("✊ 石头", "danger"), ("✌️ 剪刀", "warning"), ("🖐 布", "success")):
self._mk_btn(btn_row, text, lambda t=text.split(" ")[1]: self.fist_play(t),
kind).pack(side="left", padx=10, ipady=10)
score, score_body = self._card(wrap, "计分板")
score.pack(fill="x", pady=(14, 0))
self.fist_score = tk.Label(score_body, text="赢:0 输:0 平局:0",
font=(FONT, 14, "bold"), bg=COLORS["card"], fg=COLORS["text"])
self.fist_score.pack(anchor="w")
self._mk_btn(score_body, "结束并保存记录", self.fist_save, "primary").pack(anchor="w", pady=(10, 0))
def fist_play(self, user_choice):
f = self.game["fist"]
comp = random.choice(["石头", "剪刀", "布"])
if user_choice == comp:
f["tie"] += 1
result = "打平了,旗鼓相当。"
elif (user_choice, comp) in (("石头", "剪刀"), ("剪刀", "布"), ("布", "石头")):
f["win"] += 1
result = "你赢了!牛逼!"
else:
f["lose"] += 1
result = "你输了。再接再厉!"
f["last"] = f"你出:{user_choice} 计算机出:{comp} —— {result}"
self.fist_last.config(text=f["last"])
self.fist_score.config(text=f"赢:{f['win']} 输:{f['lose']} 平局:{f['tie']}")
def fist_save(self):
f = self.game["fist"]
if f["win"] == 0 and f["lose"] == 0 and f["tie"] == 0:
messagebox.showinfo("提示", "还没有任何比赛记录。")
return
if f["win"] > f["lose"]:
state = "赢"
elif f["win"] == f["lose"]:
state = "平局"
else:
state = "输"
if self.logged:
try:
with open(os.path.join(self.userpath, "GuessFist", "GuessFist.txt"),
"a", encoding="utf-8") as file:
file.write(f"\n赢:{f['win']}\n输:{f['lose']}\n平局:{f['tie']}\n综合:{state}\n时间:{datetime.today()}")
file.write("\n----------------")
messagebox.showinfo("已保存", "比赛记录已保存!")
except OSError as e:
messagebox.showerror("保存失败", f"写入失败:{e}")
else:
messagebox.showwarning("未保存", "你暂未登录,记录未保存。")
# --------------------------------------------------------
# 读心术实现
# --------------------------------------------------------
# 通过二进制来计算
def _build_mind_page(self, frame):
self._header(frame, "读心术", "想一个 1~31 的数字,让我猜出来")
self.game["mind"] = {"step": 0, "result": 0, "pow": 1, "cards": None}
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
card, body = self._card(wrap, "数字卡片")
card.pack(fill="both", expand=True)
self.mind_tip = tk.Label(body, text="请你想一个 1~31 的数字,然后点击开始!",
font=(FONT, 12), bg=COLORS["card"], fg=COLORS["text"])
self.mind_tip.pack(pady=(6, 4))
self.mind_cards = tk.Label(body, text="", font=(MONO, 13), bg=COLORS["card"],
fg=COLORS["primary"], justify="left")
self.mind_cards.pack(pady=8)
btns = tk.Frame(body, bg=COLORS["card"])
btns.pack(pady=12)
self.mind_btn_yes = self._mk_btn(btns, "有我的数字 ✓", lambda: self.mind_answer(1), "success")
self.mind_btn_yes.pack(side="left", padx=8)
self.mind_btn_no = self._mk_btn(btns, "没有 ✗", lambda: self.mind_answer(0), "ghost")
self.mind_btn_no.pack(side="left", padx=8)
self._mk_btn(btns, "重新开始", self.mind_reset, "warning").pack(side="left", padx=8)
def mind_reset(self):
m = self.game["mind"]
cards = []
for i in range(1, 33):
temp, bits = i, ["0"] * 6
j = 0
while temp >= 1:
bits[j] = str(temp % 2)
j += 1
temp //= 2
cards.append(bits)
m.update(step=0, result=0, pow=1, cards=cards)
self.mind_tip.config(text="请你想一个 1~31 的数字,然后点击「有我的数字 ✓ / 没有 ✗」回答每一组。")
self.mind_cards.config(text="")
self.mind_next()
def mind_next(self):
m = self.game["mind"]
if m["cards"] is None:
self.mind_reset()
return
j = m["step"]
if j >= 5:
self.mind_tip.config(text=f"🎉 你想的数是:{m['result']}!", fg=COLORS["success"])
self.mind_cards.config(text="")
self.mind_btn_yes.config(state="disabled")
self.mind_btn_no.config(state="disabled")
return
nums = [i + 1 for i in range(32) if int(m["cards"][i][j]) == 1]
self.mind_cards.config(text=" ".join(str(n) for n in nums))
self.mind_tip.config(text=f"第 {j + 1} 组(共 5 组):下面这些数字里有你想的数吗?")
self.mind_btn_yes.config(state="normal")
self.mind_btn_no.config(state="normal")
def mind_answer(self, answer):
m = self.game["mind"]
m["result"] += m["pow"] * answer
m["pow"] *= 2
m["step"] += 1
self.mind_next()
# --------------------------------------------------------
# 进制转换
# --------------------------------------------------------
def _build_base_page(self, frame):
self._header(frame, "进制转换", "十进制与任意进制互转")
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
card, body = self._card(wrap, "转换器")
card.pack(fill="x")
self.base_mode = tk.StringVar(value="dec2bin")
mode_row = tk.Frame(body, bg=COLORS["card"])
mode_row.pack(anchor="w", pady=(0, 8))
ttk.Radiobutton(mode_row, text="十进制 → 二进制", variable=self.base_mode,
value="dec2bin").pack(side="left", padx=(0, 16))
ttk.Radiobutton(mode_row, text="任意进制 → 十进制", variable=self.base_mode,
value="any2dec").pack(side="left")
_, self.base_num = self._row(body, "数字", self._mk_entry, width=24)
self.base_base_row, self.base_base = self._row(body, "进制", self._mk_entry, width=8)
self.base_base_row.pack_forget()
self.base_base_tip = tk.Label(body, text="进制如 2、8、16(仅任意进制转十进制时填写)",
font=(FONT, 9), bg=COLORS["card"], fg=COLORS["text_light"])
self.base_base_tip.pack(anchor="w", pady=(0, 4))
self.base_base_tip.pack_forget()
def toggle_mode(*_):
if self.base_mode.get() == "dec2bin":
self.base_base_row.pack_forget()
self.base_base_tip.pack_forget()
else:
self.base_base_row.pack(fill="x", pady=4)
self.base_base_tip.pack(anchor="w", pady=(0, 4))
self.base_mode.trace_add("write", toggle_mode)
self._mk_btn(body, "转 换", self.base_convert, "primary").pack(anchor="w", pady=(10, 0))
self.base_result = tk.Label(body, text="", font=(MONO, 13, "bold"),
bg=COLORS["card"], fg=COLORS["primary"])
self.base_result.pack(anchor="w", pady=(12, 0))
def base_convert(self):
try:
if self.base_mode.get() == "dec2bin":
num = int(self.base_num.get().strip())
self.base_result.config(text=f"二进制结果:{bin(num)[2:]}")
else:
num = self.base_num.get().strip()
base = int(self.base_base.get().strip())
self.base_result.config(text=f"十进制结果:{int(num, base)}")
except (ValueError, TypeError):
messagebox.showerror("错误", "输入的数字或进制不合法!")
# --------------------------------------------------------
# 计算正确率
# --------------------------------------------------------
def _build_accuracy_page(self, frame):
self._header(frame, "计算正确率", "根据题目总数与正确数计算正确率")
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
card, body = self._card(wrap, "正确率计算器")
card.pack(fill="x")
_, self.acc_total = self._row(body, "题目总数", self._mk_spinbox, from_=1, to=10 ** 9)
_, self.acc_right = self._row(body, "正确题目数", self._mk_spinbox, from_=0, to=10 ** 9)
self._mk_btn(body, "计 算", self.accuracy_calc, "primary").pack(anchor="w", pady=(10, 0))
self.acc_result = tk.Label(body, text="", font=(FONT, 14, "bold"),
bg=COLORS["card"], fg=COLORS["primary"])
self.acc_result.pack(anchor="w", pady=(12, 0))
def accuracy_calc(self):
try:
total = int(self.acc_total.get())
right = int(self.acc_right.get())
if right > total:
raise ValueError
rate = right / total * 100
self.acc_result.config(text=f"正确率:{rate:.2f}%")
except ValueError:
messagebox.showerror("错误", "输入不合法(正确数不能大于总数)!")
# --------------------------------------------------------
# 计算平均数
# --------------------------------------------------------
def _build_average_page(self, frame):
self._header(frame, "计算平均数", "输入一组数字并计算它们的平均数")
self.game["average"] = {"numbers": []}
wrap = tk.Frame(frame, bg=COLORS["bg"])
wrap.pack(fill="both", expand=True, padx=24, pady=(0, 20))
left, left_body = self._card(wrap, "数字列表")
left.pack(side="left", fill="both", expand=True, padx=(0, 12))
input_row = tk.Frame(left_body, bg=COLORS["card"])
input_row.pack(fill="x")
self.avg_input = self._mk_entry(input_row, width=14)
self.avg_input.pack(side="left", ipady=3)
self._mk_btn(input_row, "添加", self.avg_add, "primary").pack(side="left", padx=(8, 0))
self.avg_input.bind("<Return>", lambda e: self.avg_add())
self.avg_list = tk.Listbox(left_body, height=12, font=(FONT, 11),
bg="white", fg=COLORS["text"],
highlightbackground=COLORS["border"], highlightthickness=1,
selectbackground=COLORS["primary"], selectforeground="white",
relief="flat")
self.avg_list.pack(fill="both", expand=True, pady=(8, 0))
btns = tk.Frame(left_body, bg=COLORS["card"])
btns.pack(fill="x", pady=(8, 0))
self._mk_btn(btns, "删除选中", self.avg_remove, "warning").pack(side="left")
self._mk_btn(btns, "清空", self.avg_clear, "ghost").pack(side="left", padx=(8, 0))
right, right_body = self._card(wrap, "计算")
right.pack(side="left", fill="y")
right_body.config(width=260)
self.avg_delmax = tk.BooleanVar(value=True)
ttk.Checkbutton(right_body, text="去除最大值和最小值", variable=self.avg_delmax).pack(anchor="w")
self._mk_btn(right_body, "计 算 平 均 数", self.avg_calc, "success").pack(fill="x", pady=(12, 0))
self.avg_result = tk.Label(right_body, text="", font=(FONT, 12, "bold"),
bg=COLORS["card"], fg=COLORS["primary"], wraplength=240)
self.avg_result.pack(anchor="w", pady=(12, 0))
def avg_add(self):
raw = self.avg_input.get().strip()
self.avg_input.delete(0, "end")
if not raw:
return
if raw.lower() == "exit":
return
if raw.isdecimal():
self.game["average"]["numbers"].append(int(raw))
self.avg_list.insert("end", raw)
else:
messagebox.showwarning("错误", "请输入整数!")
def avg_remove(self):
sel = self.avg_list.curselection()
if not sel:
return