-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.py
More file actions
1770 lines (1526 loc) · 74.9 KB
/
Copy pathui.py
File metadata and controls
1770 lines (1526 loc) · 74.9 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
"""
EJTester - 英語・日本語単語テスト (GUI版)
tkinter を使用(Python標準ライブラリ)
"""
import csv
import random
import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox
from dataclasses import dataclass, field
# 間違えログ(mistake_log.py が同フォルダにある場合のみ使用)
try:
import importlib.util as _ilu
_ml_spec = _ilu.spec_from_file_location(
"mistake_log",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "mistake_log.py"))
_ml = _ilu.module_from_spec(_ml_spec)
_ml_spec.loader.exec_module(_ml)
except Exception:
_ml = None
# ──────────────────────────────────────────────
# データモデル
# ──────────────────────────────────────────────
@dataclass
class Word:
number: int
kanji: str
romaji: str
kana: str
word_type: str
meaning: str
def display_japanese(self) -> str:
if self.kana and self.kana != self.kanji:
return f"{self.kanji}({self.kana})"
return self.kanji
def primary_meaning(self) -> str:
return self.meaning.split(";")[0].strip()
@dataclass
class QuizResult:
total: int = 0
correct: int = 0
wrong_words: list = field(default_factory=list)
@property
def accuracy(self) -> float:
return self.correct / self.total * 100 if self.total else 0.0
# ──────────────────────────────────────────────
# CSV 読み込み
# ──────────────────────────────────────────────
def load_vocabulary(filepath: str) -> list[Word]:
words: list[Word] = []
with open(filepath, encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
words.append(Word(
number=int(row["#"]),
kanji=row["ごい"].strip(),
romaji=row["ローマ字"].strip(),
kana=row["かな"].strip(),
word_type=row["Type"].strip(),
meaning=row["Meaning"].strip(),
))
return words
# ──────────────────────────────────────────────
# カラー・フォント定数
# ──────────────────────────────────────────────
BG = "#1e1e2e"
BG2 = "#2a2a3e"
BG3 = "#313145"
ACCENT = "#7c6af7"
ACCENT2 = "#a78bfa"
GREEN = "#4ade80"
RED = "#f87171"
YELLOW = "#fbbf24"
TEXT = "#e2e8f0"
TEXT_DIM = "#94a3b8"
BORDER = "#3f3f5a"
FONT_TITLE = ("Segoe UI", 22, "bold")
FONT_HEAD = ("Segoe UI", 14, "bold")
FONT_BODY = ("Segoe UI", 12)
FONT_BODY_B = ("Segoe UI", 12, "bold")
FONT_SMALL = ("Segoe UI", 10)
FONT_KANJI = ("Meiryo UI", 28, "bold")
FONT_KANA = ("Meiryo UI", 14)
# ──────────────────────────────────────────────
# メインアプリケーション
# ──────────────────────────────────────────────
class EJTesterApp(tk.Tk):
def __init__(self, words: list[Word]):
super().__init__()
self.words = words
self.title("EJTester — 英語・日本語 単語テスト")
self.geometry("860x640")
self.minsize(720, 540)
self.configure(bg=BG)
self.resizable(True, True)
# アイコン(エラーは無視)
try:
self.iconbitmap(default="")
except Exception:
pass
self._frame: tk.Frame | None = None
self.show_menu()
# ── フレーム切り替え ──────────────────────
def switch_frame(self, frame_class, **kwargs):
if self._frame:
self._frame.destroy()
self._frame = frame_class(self, **kwargs)
self._frame.pack(fill="both", expand=True)
def show_menu(self):
self.switch_frame(MenuFrame)
def show_word_list(self):
self.switch_frame(WordListFrame, words=self.words)
def show_flashcards(self):
self.switch_frame(FlashCardFrame, words=self.words)
def show_settings(self):
self.switch_frame(SettingsFrame, words=self.words)
def show_weak_settings(self):
self.switch_frame(WeakWordSettingsFrame, words=self.words)
def start_quiz(self, quiz_words: list[Word], mode: str, all_words: list[Word]):
# 直前のテスト設定を記憶しておく(再テスト用)
self._last_mode = mode
self._last_all_words = all_words
self.switch_frame(ListQuizFrame,
quiz_words=quiz_words,
mode=mode,
all_words=all_words)
def retry_wrong(self, wrong_words: list[Word]):
"""間違えた単語だけを、前回と同じモードで再テストする"""
mode = getattr(self, "_last_mode", "1")
all_words = getattr(self, "_last_all_words", wrong_words)
quiz_words = list(wrong_words)
random.shuffle(quiz_words)
self.start_quiz(quiz_words, mode, all_words)
def show_result(self, result: QuizResult):
self.switch_frame(ResultFrame, result=result)
# ──────────────────────────────────────────────
# ユーティリティ ウィジェット
# ──────────────────────────────────────────────
def styled_button(parent, text, command, color=ACCENT, width=18, font=FONT_BODY_B):
btn = tk.Button(
parent, text=text, command=command,
bg=color, fg=TEXT, activebackground=ACCENT2, activeforeground=TEXT,
font=font, relief="flat", cursor="hand2",
padx=16, pady=10, width=width, bd=0,
)
btn.bind("<Enter>", lambda e: btn.config(bg=ACCENT2))
btn.bind("<Leave>", lambda e: btn.config(bg=color))
return btn
def section_label(parent, text, font=FONT_HEAD, fg=TEXT):
return tk.Label(parent, text=text, bg=BG, fg=fg, font=font)
# ──────────────────────────────────────────────
# メニュー画面
# ──────────────────────────────────────────────
class MenuFrame(tk.Frame):
def __init__(self, master: EJTesterApp):
super().__init__(master, bg=BG)
self.master: EJTesterApp
# ヘッダー
header = tk.Frame(self, bg=BG2, pady=28)
header.pack(fill="x")
tk.Label(header, text="🗾 EJTester", font=FONT_TITLE,
bg=BG2, fg=ACCENT2).pack()
tk.Label(header, text="英語・日本語 単語テスト", font=FONT_BODY,
bg=BG2, fg=TEXT_DIM).pack(pady=(4, 0))
# 単語数バッジ
badge_frame = tk.Frame(self, bg=BG3, pady=12)
badge_frame.pack(fill="x", padx=60, pady=(20, 0))
tk.Label(badge_frame, text=f"📚 登録単語数: {len(master.words)} 語",
font=FONT_BODY_B, bg=BG3, fg=YELLOW).pack()
# ボタン
btn_frame = tk.Frame(self, bg=BG, pady=30)
btn_frame.pack()
buttons = [
("▶ テストを開始する", master.show_settings, ACCENT),
("🔥 苦手単語テスト", master.show_weak_settings, "#7a2a2a"),
("🃏 フラッシュカード", master.show_flashcards, "#2d6a4f"),
("📖 単語一覧を見る", master.show_word_list, BG3),
("✖ 終了", master.quit, "#4a4a6a"),
]
for label, cmd, color in buttons:
styled_button(btn_frame, label, cmd, color=color, width=24).pack(pady=8)
# フッター
tk.Label(self, text="vocabulary.csv を編集して単語を追加できます",
font=FONT_SMALL, bg=BG, fg=TEXT_DIM).pack(side="bottom", pady=10)
# ──────────────────────────────────────────────
# テスト設定画面
# ──────────────────────────────────────────────
class SettingsFrame(tk.Frame):
def __init__(self, master: EJTesterApp, words: list[Word]):
super().__init__(master, bg=BG)
self.master: EJTesterApp
self.all_words = words
# ── タイトル ──
tk.Label(self, text="テスト設定", font=FONT_TITLE,
bg=BG, fg=ACCENT2, pady=20).pack()
inner = tk.Frame(self, bg=BG2, padx=40, pady=30)
inner.pack(padx=60, fill="x")
# ── 出題モード ──
section_label(inner, "出題モード").grid(row=0, column=0, sticky="w", pady=(0, 6))
self.mode_var = tk.StringVar(value="1")
modes = [
("1", "日本語 → 英語(4択)"),
("2", "日本語 → 英語(記述)"),
("3", "英語 → 日本語(記述)"),
("4", "ローマ字 → 日本語(4択)"),
("5", "ランダム(全モード混合)"),
]
mode_frame = tk.Frame(inner, bg=BG2)
mode_frame.grid(row=1, column=0, sticky="w", pady=(0, 20))
for val, label in modes:
tk.Radiobutton(
mode_frame, text=label, variable=self.mode_var, value=val,
bg=BG2, fg=TEXT, selectcolor=BG3, activebackground=BG2,
activeforeground=ACCENT2, font=FONT_BODY, indicatoron=True,
).pack(anchor="w", pady=2)
# ── 番号範囲 ──
section_label(inner, "番号範囲").grid(row=2, column=0, sticky="w", pady=(0, 6))
# 単語番号の最小・最大を自動取得
all_nums = sorted(w.number for w in words)
num_min, num_max = all_nums[0], all_nums[-1]
# 100 単位でチェックボックスを生成
import math
chunk = 100
chunks = []
lo = num_min
while lo <= num_max:
hi = min(lo + chunk - 1, num_max)
chunks.append((lo, hi))
lo += chunk
self.range_chunk_vars: dict[tuple, tk.BooleanVar] = {}
range_chunk_frame = tk.Frame(inner, bg=BG2)
range_chunk_frame.grid(row=3, column=0, sticky="w", pady=(0, 6))
for lo, hi in chunks:
cnt = sum(1 for w in words if lo <= w.number <= hi)
var = tk.BooleanVar(value=True)
self.range_chunk_vars[(lo, hi)] = var
tk.Checkbutton(
range_chunk_frame,
text=f" {lo} 〜 {hi} ({cnt} 語)",
variable=var,
bg=BG2, fg=TEXT, selectcolor=BG3,
activebackground=BG2, activeforeground=ACCENT2,
font=FONT_BODY,
).pack(anchor="w", pady=2)
# ── 出題範囲 ──
section_label(inner, "出題範囲").grid(row=4, column=0, sticky="w", pady=(0, 6))
self.range_var = tk.StringVar(value="all")
ranges = [
("all", f"すべての単語(選択した番号範囲内)"),
("random", "ランダムに選ぶ"),
("type", "品詞で絞り込む"),
]
range_frame = tk.Frame(inner, bg=BG2)
range_frame.grid(row=5, column=0, sticky="w", pady=(0, 20))
for val, label in ranges:
tk.Radiobutton(
range_frame, text=label, variable=self.range_var, value=val,
bg=BG2, fg=TEXT, selectcolor=BG3, activebackground=BG2,
activeforeground=ACCENT2, font=FONT_BODY,
command=self._on_range_change,
).pack(anchor="w", pady=2)
# ランダム問題数
self.count_frame = tk.Frame(inner, bg=BG2)
self.count_frame.grid(row=6, column=0, sticky="w", pady=(0, 10))
tk.Label(self.count_frame, text="問題数:", font=FONT_BODY,
bg=BG2, fg=TEXT).pack(side="left")
self.count_var = tk.IntVar(value=min(20, len(words)))
self.count_spin = tk.Spinbox(
self.count_frame, from_=1, to=len(words),
textvariable=self.count_var, width=6,
font=FONT_BODY, bg=BG3, fg=TEXT, buttonbackground=BG3,
relief="flat", bd=4,
)
self.count_spin.pack(side="left", padx=8)
tk.Label(self.count_frame, text=f"語 (最大 {len(words)} 語)",
font=FONT_SMALL, bg=BG2, fg=TEXT_DIM).pack(side="left")
self.count_frame.grid_remove()
# 品詞フィルタ
self.type_frame = tk.Frame(inner, bg=BG2)
self.type_frame.grid(row=7, column=0, sticky="w", pady=(0, 10))
self.type_vars: dict[str, tk.BooleanVar] = {}
types = sorted(set(w.word_type for w in words))
cols = 2
for idx, t in enumerate(types):
var = tk.BooleanVar(value=True)
self.type_vars[t] = var
count = sum(1 for w in words if w.word_type == t)
cb = tk.Checkbutton(
self.type_frame, text=f"{t} ({count}語)",
variable=var, bg=BG2, fg=TEXT,
selectcolor=BG3, activebackground=BG2,
activeforeground=ACCENT2, font=FONT_SMALL,
)
cb.grid(row=idx // cols, column=idx % cols, sticky="w", padx=(0, 20), pady=2)
self.type_frame.grid_remove()
# ── ボタン ──
btn_row = tk.Frame(self, bg=BG, pady=20)
btn_row.pack()
styled_button(btn_row, "▶ テスト開始", self._start, ACCENT).pack(side="left", padx=10)
styled_button(btn_row, "← 戻る", master.show_menu, BG3, width=10).pack(side="left", padx=10)
def _on_range_change(self):
val = self.range_var.get()
self.count_frame.grid_remove()
self.type_frame.grid_remove()
if val == "random":
self.count_frame.grid()
elif val == "type":
self.type_frame.grid()
def _start(self):
mode = self.mode_var.get()
r = self.range_var.get()
# ── 番号範囲でまず絞り込む ──
selected_chunks = [
(lo, hi) for (lo, hi), v in self.range_chunk_vars.items() if v.get()
]
if not selected_chunks:
messagebox.showwarning("警告", "少なくとも1つの番号範囲を選んでください。")
return
base_words = [
w for w in self.all_words
if any(lo <= w.number <= hi for lo, hi in selected_chunks)
]
if not base_words:
messagebox.showwarning("警告", "選択した番号範囲に単語がありません。")
return
if r == "all":
quiz_words = list(base_words)
random.shuffle(quiz_words)
elif r == "random":
n = self.count_var.get()
quiz_words = random.sample(base_words, min(n, len(base_words)))
else: # type
selected_types = [t for t, v in self.type_vars.items() if v.get()]
if not selected_types:
messagebox.showwarning("警告", "少なくとも1つの品詞を選んでください。")
return
filtered = [w for w in base_words if w.word_type in selected_types]
if not filtered:
messagebox.showwarning("警告", "選択した条件に一致する単語がありません。")
return
quiz_words = list(filtered)
random.shuffle(quiz_words)
self.master.start_quiz(quiz_words, mode, self.all_words)
# ──────────────────────────────────────────────
# 苦手単語テスト設定画面
# ──────────────────────────────────────────────
WEAK_RED = "#c0392b" # 苦手テスト固有のアクセント色
class WeakWordSettingsFrame(tk.Frame):
"""間違え回数の多い単語を優先して出題する設定画面。"""
def __init__(self, master: EJTesterApp, words: list[Word]):
super().__init__(master, bg=BG)
self.master: EJTesterApp
self.all_words = words
# ── 間違えログを読み込む ──
self._log: dict[str, int] = _ml.load_log() if _ml else {}
# 間違え回数付きの単語リスト(回数 > 0 のみ)
self._weak: list[tuple[int, Word]] = sorted(
[(self._log.get(str(w.number), 0), w)
for w in words if self._log.get(str(w.number), 0) > 0],
key=lambda x: -x[0]
)
# ── タイトル ──
header = tk.Frame(self, bg=BG2, padx=20, pady=16)
header.pack(fill="x")
tk.Label(header, text="🔥 苦手単語テスト",
font=FONT_TITLE, bg=BG2, fg="#f87171").pack(side="left")
# ── メインコンテンツ(左:設定 / 右:苦手単語プレビュー) ──
content = tk.Frame(self, bg=BG)
content.pack(fill="both", expand=True, padx=20, pady=10)
content.columnconfigure(0, weight=1)
content.columnconfigure(1, weight=2)
content.rowconfigure(0, weight=1)
# ── 左:設定パネル ──
left = tk.Frame(content, bg=BG2, padx=24, pady=20)
left.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
if not self._weak:
tk.Label(left, text="まだ間違えた単語の\n記録がありません。",
font=FONT_BODY, bg=BG2, fg=TEXT_DIM,
justify="center").pack(pady=30)
tk.Label(left, text="通常のテストで間違えると\nここに蓄積されます。",
font=FONT_SMALL, bg=BG2, fg=TEXT_DIM,
justify="center").pack()
styled_button(left, "← 戻る", master.show_menu, BG3, width=14).pack(pady=20)
# 右パネルは空
tk.Frame(content, bg=BG).grid(row=0, column=1, sticky="nsew")
return
# ── 出題モード ──
section_label(left, "出題モード", fg=TEXT).pack(anchor="w", pady=(0, 6))
self.mode_var = tk.StringVar(value="1")
modes = [
("1", "日本語 → 英語(4択)"),
("2", "日本語 → 英語(記述)"),
("3", "英語 → 日本語(記述)"),
("4", "ローマ字 → 日本語(4択)"),
("5", "ランダム(全モード混合)"),
]
for val, label in modes:
tk.Radiobutton(
left, text=label, variable=self.mode_var, value=val,
bg=BG2, fg=TEXT, selectcolor=BG3, activebackground=BG2,
activeforeground=ACCENT2, font=FONT_BODY,
).pack(anchor="w", pady=2)
tk.Frame(left, bg=BORDER, height=1).pack(fill="x", pady=12)
# ── 出題数・しきい値 ──
section_label(left, "出題設定", fg=TEXT).pack(anchor="w", pady=(0, 8))
count_row = tk.Frame(left, bg=BG2)
count_row.pack(anchor="w", pady=4)
tk.Label(count_row, text="出題数:", font=FONT_BODY, bg=BG2, fg=TEXT).pack(side="left")
self.count_var = tk.IntVar(value=min(20, len(self._weak)))
tk.Spinbox(
count_row, from_=1, to=len(self._weak),
textvariable=self.count_var, width=5,
font=FONT_BODY, bg=BG3, fg=TEXT, buttonbackground=BG3,
relief="flat", bd=4,
).pack(side="left", padx=8)
tk.Label(count_row, text=f"語 (最大 {len(self._weak)} 語)",
font=FONT_SMALL, bg=BG2, fg=TEXT_DIM).pack(side="left")
min_row = tk.Frame(left, bg=BG2)
min_row.pack(anchor="w", pady=4)
tk.Label(min_row, text="最小間違え回数:", font=FONT_BODY, bg=BG2, fg=TEXT).pack(side="left")
max_mistakes = self._weak[0][0] if self._weak else 1
self.min_wrong_var = tk.IntVar(value=1)
tk.Spinbox(
min_row, from_=1, to=max(max_mistakes, 1),
textvariable=self.min_wrong_var, width=4,
font=FONT_BODY, bg=BG3, fg=TEXT, buttonbackground=BG3,
relief="flat", bd=4,
command=self._refresh_preview,
).pack(side="left", padx=8)
tk.Label(min_row, text="回以上",
font=FONT_SMALL, bg=BG2, fg=TEXT_DIM).pack(side="left")
tk.Frame(left, bg=BORDER, height=1).pack(fill="x", pady=12)
# ── リセットボタン ──
tk.Button(left, text="🗑 間違えログをリセット",
command=self._reset_log,
bg="#4a1a1a", fg=TEXT, font=FONT_SMALL,
relief="flat", cursor="hand2", padx=10, pady=6).pack(anchor="w", pady=(0, 10))
# ── アクションボタン ──
btn_row = tk.Frame(left, bg=BG2)
btn_row.pack(anchor="w", pady=(4, 0))
styled_button(btn_row, "🔥 テスト開始", self._start,
WEAK_RED, width=14).pack(side="left", padx=(0, 8))
styled_button(btn_row, "← 戻る", master.show_menu,
BG3, width=8).pack(side="left")
# ── 右:苦手単語プレビュー ──
right = tk.Frame(content, bg=BG2, padx=16, pady=16)
right.grid(row=0, column=1, sticky="nsew")
tk.Label(right, text="📊 間違え回数ランキング",
font=FONT_HEAD, bg=BG2, fg=ACCENT2).pack(anchor="w", pady=(0, 8))
list_frame = tk.Frame(right, bg=BG2)
list_frame.pack(fill="both", expand=True)
vsb = tk.Scrollbar(list_frame)
vsb.pack(side="right", fill="y")
cols = ("No.", "日本語", "ローマ字", "意味", "間違え回数")
self.preview_tree = ttk.Treeview(
list_frame, columns=cols, show="headings",
yscrollcommand=vsb.set, height=16)
vsb.config(command=self.preview_tree.yview)
s = ttk.Style()
s.configure("Weak.Treeview",
background=BG2, foreground=TEXT,
fieldbackground=BG2, rowheight=26, font=FONT_SMALL)
s.configure("Weak.Treeview.Heading",
background=BG3, foreground=ACCENT2, font=FONT_SMALL)
s.map("Weak.Treeview", background=[("selected", BG3)])
self.preview_tree.config(style="Weak.Treeview")
col_widths = {"No.": 40, "日本語": 130, "ローマ字": 110,
"意味": 250, "間違え回数": 80}
for col in cols:
self.preview_tree.heading(col, text=col)
self.preview_tree.column(col, width=col_widths[col], anchor="w")
self.preview_tree.pack(side="left", fill="both", expand=True)
# タグ:回数に応じた色
self.preview_tree.tag_configure("high", foreground=RED)
self.preview_tree.tag_configure("medium", foreground=YELLOW)
self.preview_tree.tag_configure("low", foreground=TEXT)
self._refresh_preview()
def _refresh_preview(self):
"""しきい値に応じてプレビューリストを更新する"""
if not hasattr(self, "preview_tree"):
return
self.preview_tree.delete(*self.preview_tree.get_children())
try:
min_w = self.min_wrong_var.get()
except Exception:
min_w = 1
filtered = [(cnt, w) for cnt, w in self._weak if cnt >= min_w]
for cnt, w in filtered:
if cnt >= 5:
tag = "high"
elif cnt >= 3:
tag = "medium"
else:
tag = "low"
self.preview_tree.insert("", "end",
values=(w.number, w.display_japanese(), w.romaji, w.meaning, f"❌ {cnt}回"),
tags=(tag,))
# 出題数の最大値を更新
if hasattr(self, "count_var"):
n = max(1, len(filtered))
self.count_var.set(min(self.count_var.get(), n))
def _reset_log(self):
if not messagebox.askyesno("確認",
"間違えログを全てリセットしますか?\nこの操作は元に戻せません。"):
return
if _ml:
_ml.reset_log()
self._log = {}
self._weak = []
messagebox.showinfo("完了", "間違えログをリセットしました。")
self.master.show_menu()
def _start(self):
try:
min_w = self.min_wrong_var.get()
n = self.count_var.get()
except Exception:
return
filtered = [(cnt, w) for cnt, w in self._weak if cnt >= min_w]
if not filtered:
messagebox.showwarning("警告",
"条件に一致する苦手単語がありません。\nしきい値を下げてみてください。")
return
# 間違え回数の多い順に並べ、上位 n 件を出題
quiz_words = [w for _, w in filtered[:n]]
random.shuffle(quiz_words)
mode = self.mode_var.get()
self.master.start_quiz(quiz_words, mode, self.all_words)
# ──────────────────────────────────────────────
# クイズ画面
# ──────────────────────────────────────────────
class QuizFrame(tk.Frame):
def __init__(self, master: EJTesterApp,
quiz_words: list[Word], mode: str, all_words: list[Word]):
super().__init__(master, bg=BG)
self.master: EJTesterApp
self.quiz_words = quiz_words
self.mode = mode
self.all_words = all_words
self.result = QuizResult()
self.index = 0
self.answered = False
self.choice_btns: list[tk.Button] = []
self._build_ui()
self._load_question()
# ── UI 構築 ──
def _build_ui(self):
total = len(self.quiz_words)
# ── トップバー ──
top = tk.Frame(self, bg=BG2, padx=20, pady=12)
top.pack(fill="x")
left_top = tk.Frame(top, bg=BG2)
left_top.pack(side="left")
self.lbl_progress = tk.Label(left_top, text="", font=FONT_BODY_B, bg=BG2, fg=TEXT)
self.lbl_progress.pack(anchor="w")
self.lbl_score = tk.Label(left_top, text="", font=FONT_SMALL, bg=BG2, fg=TEXT_DIM)
self.lbl_score.pack(anchor="w")
# プログレスバー
bar_frame = tk.Frame(top, bg=BG2)
bar_frame.pack(side="right", fill="x", expand=True, padx=(20, 0))
self.progress_var = tk.DoubleVar(value=0)
style = ttk.Style()
style.theme_use("clam")
style.configure("Accent.Horizontal.TProgressbar",
troughcolor=BG3, background=ACCENT, thickness=10)
self.progressbar = ttk.Progressbar(
bar_frame, variable=self.progress_var,
maximum=total, style="Accent.Horizontal.TProgressbar", length=300)
self.progressbar.pack(side="right", pady=8)
# ── 問題エリア ──
q_frame = tk.Frame(self, bg=BG3, padx=30, pady=24)
q_frame.pack(fill="x", padx=30, pady=(20, 10))
self.lbl_mode_hint = tk.Label(q_frame, text="", font=FONT_SMALL,
bg=BG3, fg=TEXT_DIM)
self.lbl_mode_hint.pack(anchor="w")
self.lbl_question = tk.Label(q_frame, text="", font=FONT_KANJI,
bg=BG3, fg=TEXT, wraplength=700, justify="center")
self.lbl_question.pack(pady=(8, 4))
self.lbl_sub = tk.Label(q_frame, text="", font=FONT_KANA,
bg=BG3, fg=TEXT_DIM)
self.lbl_sub.pack()
self.lbl_hint = tk.Label(q_frame, text="", font=FONT_SMALL,
bg=BG3, fg=TEXT_DIM)
self.lbl_hint.pack(pady=(4, 0))
# ── 回答エリア ──
self.answer_frame = tk.Frame(self, bg=BG, padx=30, pady=10)
self.answer_frame.pack(fill="x")
# 記述入力
self.entry_frame = tk.Frame(self.answer_frame, bg=BG)
self.entry_var = tk.StringVar()
self.entry = tk.Entry(
self.entry_frame, textvariable=self.entry_var,
font=FONT_BODY, bg=BG3, fg=TEXT, insertbackground=TEXT,
relief="flat", bd=8, width=40,
)
self.entry.pack(side="left", ipady=6)
self.btn_submit = styled_button(
self.entry_frame, "回答する", self._submit_text, ACCENT, width=10)
self.btn_submit.pack(side="left", padx=10)
self.entry.bind("<Return>", lambda e: self._submit_text())
# 4択ボタン
self.choice_frame = tk.Frame(self.answer_frame, bg=BG)
for _ in range(4):
btn = tk.Button(
self.choice_frame, text="", font=FONT_BODY,
bg=BG3, fg=TEXT, activebackground=BG2, activeforeground=TEXT,
relief="flat", cursor="hand2", wraplength=360, justify="left",
padx=16, pady=12, bd=0,
)
btn.pack(fill="x", pady=5)
self.choice_btns.append(btn)
# ── フィードバック ──
self.lbl_feedback = tk.Label(self, text="", font=FONT_BODY_B,
bg=BG, fg=GREEN, pady=4)
self.lbl_feedback.pack()
self.lbl_answer_reveal = tk.Label(self, text="", font=FONT_BODY,
bg=BG, fg=TEXT_DIM, wraplength=700)
self.lbl_answer_reveal.pack()
# ── 次へボタン ──
self.btn_next = styled_button(self, "次の問題 →", self._next_question, ACCENT, width=16)
self.btn_next.pack(pady=12)
self.btn_next.pack_forget()
# ── 問題読み込み ──
def _load_question(self):
self.answered = False
self.lbl_feedback.config(text="")
self.lbl_answer_reveal.config(text="")
self.btn_next.pack_forget()
self.entry_frame.pack_forget()
self.choice_frame.pack_forget()
total = len(self.quiz_words)
i = self.index
q = self.quiz_words[i]
# プログレス更新
self.progress_var.set(i)
self.lbl_progress.config(text=f"問題 {i + 1} / {total}")
self.lbl_score.config(
text=f"✅ 正解 {self.result.correct} ❌ 不正解 {self.result.correct + (i - self.result.correct)- (i - self.result.correct)}")
self.lbl_score.config(
text=f"✅ 正解 {self.result.correct} ❌ 不正解 {i - self.result.correct}")
# モード決定
mode = self.mode if self.mode != "5" else random.choice(["1", "2", "3", "4"])
self._current_mode = mode
self._current_word = q
mode_hints = {
"1": "日本語 → 英語(4択)",
"2": "日本語 → 英語(記述)",
"3": "英語 → 日本語(記述)",
"4": "ローマ字 → 日本語(4択)",
}
self.lbl_mode_hint.config(text=f"モード: {mode_hints[mode]} | 品詞: {q.word_type}")
if mode == "1":
# 日本語 → 英語 4択
self.lbl_question.config(text=q.display_japanese(), font=FONT_KANJI)
self.lbl_sub.config(text=f"({q.romaji})")
self.lbl_hint.config(text="")
self._show_choices_meaning(q)
elif mode == "2":
# 日本語 → 英語 記述
self.lbl_question.config(text=q.display_japanese(), font=FONT_KANJI)
self.lbl_sub.config(text=f"({q.romaji})")
self.lbl_hint.config(text="英語で意味を入力してください")
self._show_entry()
elif mode == "3":
# 英語 → 日本語 記述
self.lbl_question.config(text=q.meaning, font=FONT_BODY_B)
self.lbl_sub.config(text="")
self.lbl_hint.config(text="日本語(漢字・ひらがな・カタカナ・ローマ字)を入力してください")
self._show_entry()
elif mode == "4":
# ローマ字 → 日本語 4択
self.lbl_question.config(text=q.romaji, font=FONT_KANJI)
self.lbl_sub.config(text=f"意味: {q.primary_meaning()}")
self.lbl_hint.config(text="")
self._show_choices_japanese(q)
def _show_entry(self):
self.entry_var.set("")
self.entry_frame.pack(pady=10)
self.entry.focus_set()
def _show_choices_meaning(self, q: Word):
others = [w for w in self.all_words if w.number != q.number]
distractors = random.sample(others, min(3, len(others)))
choices = [q.meaning] + [d.meaning for d in distractors]
random.shuffle(choices)
self._choices = choices
self.choice_frame.pack(fill="x", pady=10)
for i, (btn, text) in enumerate(zip(self.choice_btns, choices)):
btn.config(
text=f" {i+1}. {text}", bg=BG3, fg=TEXT,
command=lambda c=text: self._submit_choice_meaning(c),
state="normal",
)
btn.bind("<Enter>", lambda e, b=btn: b.config(bg=BG2) if b["state"] == "normal" else None)
btn.bind("<Leave>", lambda e, b=btn: b.config(bg=BG3) if b["state"] != "disabled" and b["bg"] not in (GREEN, RED) else None)
def _show_choices_japanese(self, q: Word):
others = [w for w in self.all_words if w.number != q.number]
distractors = random.sample(others, min(3, len(others)))
choices = [q.display_japanese()] + [d.display_japanese() for d in distractors]
random.shuffle(choices)
self._choices_jp = choices
self.choice_frame.pack(fill="x", pady=10)
for i, (btn, text) in enumerate(zip(self.choice_btns, choices)):
btn.config(
text=f" {i+1}. {text}", bg=BG3, fg=TEXT,
command=lambda c=text: self._submit_choice_jp(c),
state="normal",
)
btn.bind("<Enter>", lambda e, b=btn: b.config(bg=BG2) if b["state"] == "normal" else None)
btn.bind("<Leave>", lambda e, b=btn: b.config(bg=BG3) if b["state"] != "disabled" and b["bg"] not in (GREEN, RED) else None)
# ── 回答処理 ──
def _submit_text(self):
if self.answered:
return
q = self._current_word
answer = self.entry_var.get().strip()
if not answer:
return
self.answered = True
self.entry.config(state="disabled")
self.btn_submit.config(state="disabled")
if self._current_mode == "2":
meanings = [m.strip().lower() for m in q.meaning.replace(";", ",").split(",")]
ok = any(answer.lower() == m for m in meanings) or answer.lower() in q.meaning.lower()
correct_text = q.meaning
else: # mode 3
correct_answers = [a for a in [q.kanji, q.kana, q.romaji] if a]
ok = answer in correct_answers
correct_text = f"{q.display_japanese()}({q.romaji})"
self._show_feedback(ok, correct_text)
def _submit_choice_meaning(self, selected: str):
if self.answered:
return
self.answered = True
q = self._current_word
ok = selected == q.meaning
for btn in self.choice_btns:
btn.config(state="disabled")
if btn["text"].endswith(q.meaning) or q.meaning in btn["text"]:
btn.config(bg=GREEN, fg=BG)
elif btn["text"].endswith(selected) or selected in btn["text"]:
if not ok:
btn.config(bg=RED, fg=TEXT)
self._show_feedback(ok, q.meaning, highlight_done=True)
def _submit_choice_jp(self, selected: str):
if self.answered:
return
self.answered = True
q = self._current_word
correct = q.display_japanese()
ok = selected == correct
for btn in self.choice_btns:
btn.config(state="disabled")
if correct in btn["text"]:
btn.config(bg=GREEN, fg=BG)
elif selected in btn["text"] and not ok:
btn.config(bg=RED, fg=TEXT)
self._show_feedback(ok, correct, highlight_done=True)
def _show_feedback(self, ok: bool, correct_text: str, highlight_done: bool = False):
q = self._current_word
if ok:
self.result.correct += 1
self.lbl_feedback.config(text="✅ 正解!", fg=GREEN)
self.lbl_answer_reveal.config(
text=f"{q.display_japanese()}({q.romaji}) → {q.meaning}", fg=TEXT_DIM)
else:
self.result.wrong_words.append(q)
self.lbl_feedback.config(text="❌ 不正解", fg=RED)
self.lbl_answer_reveal.config(
text=f"正解は: {correct_text}", fg=YELLOW)
self.result.total += 1
self.btn_next.pack(pady=12)
# ラスト問題なら「結果を見る」に変更
if self.index >= len(self.quiz_words) - 1:
self.btn_next.config(text="結果を見る 📊", command=self._finish)
# ── 次の問題 ──
def _next_question(self):
self.index += 1
if self.index >= len(self.quiz_words):
self._finish()
else:
self._load_question()
def _finish(self):
self.progress_var.set(len(self.quiz_words))
self.master.show_result(self.result)
# ──────────────────────────────────────────────
# リスト式テスト画面(インライン入力・Tab移動対応)
# ──────────────────────────────────────────────
class ListQuizFrame(tk.Frame):
"""全問をスクロール可能なグリッドで表示。
各行に Entry(記述)または OptionMenu(4択)を直接配置。
Tab / Shift+Tab で次・前の入力欄へ移動。
Enter で採点。全問採点後に「結果を見る」が有効化。
"""
ROW_H = 36 # 1行の高さ(px)
PAD_X = 6
PAD_Y = 2
def __init__(self, master: EJTesterApp,
quiz_words: list[Word], mode: str, all_words: list[Word]):
super().__init__(master, bg=BG)
self.master: EJTesterApp
self.quiz_words = quiz_words
self.mode = mode
self.all_words = all_words
self.result = QuizResult()
self.states: list[str | None] = [None] * len(quiz_words)
self.modes: list[str] = [
mode if mode != "5" else random.choice(["1", "2", "3", "4"])
for _ in quiz_words
]
# 各行のウィジェット参照
self.entries: list[tk.Entry | None] = [None] * len(quiz_words)
self.entry_vars: list[tk.StringVar] = [tk.StringVar() for _ in quiz_words]
self.result_labels: list[tk.Label | None] = [None] * len(quiz_words)
self.row_frames: list[tk.Frame] = []
self._build_ui()
# ── UI 構築 ──────────────────────────────
def _build_ui(self):
total = len(self.quiz_words)
# ── トップバー ──
top = tk.Frame(self, bg=BG2, padx=16, pady=10)
top.pack(fill="x")
left = tk.Frame(top, bg=BG2)
left.pack(side="left")
mode_labels = {
"1": "日本語 → 英語(4択)",
"2": "日本語 → 英語(記述)",
"3": "英語 → 日本語(記述)",
"4": "ローマ字 → 日本語(4択)",
"5": "ランダム(全モード混合)",
}
tk.Label(left, text=f"📝 {mode_labels.get(self.mode, '')}",
font=FONT_HEAD, bg=BG2, fg=ACCENT2).pack(anchor="w")
tk.Label(left, text="Tab / Shift+Tab で移動 Enter で採点",
font=FONT_SMALL, bg=BG2, fg=TEXT_DIM).pack(anchor="w")
self.lbl_score = tk.Label(
top, text=f"✅ 0 ❌ 0 / 残 {total}",
font=FONT_BODY_B, bg=BG2, fg=TEXT)
self.lbl_score.pack(side="right", padx=8)
# プログレスバー
bar_outer = tk.Frame(self, bg=BG, pady=3)
bar_outer.pack(fill="x", padx=16)
self.progress_var = tk.DoubleVar(value=0)
s = ttk.Style()
s.configure("LQ.Horizontal.TProgressbar",
troughcolor=BG3, background=ACCENT, thickness=7)
ttk.Progressbar(bar_outer, variable=self.progress_var,
maximum=total,
style="LQ.Horizontal.TProgressbar").pack(fill="x")
# ── ヘッダー行 ──
header = tk.Frame(self, bg=BG3)
header.pack(fill="x", padx=16, pady=(4, 0))
self._make_header(header)
# ── スクロール可能なリスト ──
outer = tk.Frame(self, bg=BG)
outer.pack(fill="both", expand=True, padx=16, pady=(0, 4))
self.canvas = tk.Canvas(outer, bg=BG, highlightthickness=0)
vsb = tk.Scrollbar(outer, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.inner = tk.Frame(self.canvas, bg=BG)
self._canvas_win = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")