こんにちは!
今回は、PythonのGUIライブラリ「Tkinter」を使って作る、シンプルな単語帳クイズアプリを紹介します。
英単語の意味を4択問題で出題し、正解・不正解の履歴も記録できます。
読み上げ機能を省いているので、環境による音声再生の問題もありません。
初心者の方でも理解しやすい構成になっているので、ぜひチャレンジしてみてください!
この記事で作るもの
- 単語の意味を当てる4択クイズアプリ
- 正解・不正解の回数を記録(JSONファイルに保存)
- GUI画面で問題と選択肢を表示
- 正解、不正解を色でわかりやすくフィードバック
- 終了時に正答率を表示
コード解説
import tkinter as tk
from tkinter import messagebox
import json
import random
import os
FILENAME = "words_data.json"
# 初期の単語データ(英単語:意味、正解数、不正解数)
initial_words = {
"apple": {"meaning": "りんご", "correct": 0, "wrong": 0},
"dog": {"meaning": "犬", "correct": 0, "wrong": 0},
"cat": {"meaning": "猫", "correct": 0, "wrong": 0},
# ...(必要に応じて単語を追加してください)
}
# JSONファイルに単語データを保存
def save_words(words):
with open(FILENAME, "w", encoding="utf-8") as f:
json.dump(words, f, ensure_ascii=False, indent=2)
# JSONファイルから単語データを読み込み。なければ初期データを保存して読み込む
def load_words():
if os.path.exists(FILENAME):
try:
with open(FILENAME, "r", encoding="utf-8") as f:
data = json.load(f)
if not data:
return initial_words
return data
except Exception as e:
print("読み込み失敗:", e)
return initial_words
else:
save_words(initial_words)
return initial_words
words = load_words()
current_word = None
choices = []
# クイズ問題を出題
def quiz():
global current_word, choices
if not words:
messagebox.showerror("エラー", "単語データがありません。")
return
current_word = random.choice(list(words.keys()))
correct_meaning = words[current_word]['meaning']
wrong_meanings = [words[w]['meaning'] for w in words if w != current_word]
max_choices = min(4, len(words))
num_wrong_choices = max_choices - 1
wrong_choices = random.sample(wrong_meanings, min(num_wrong_choices, len(wrong_meanings)))
choices = wrong_choices + [correct_meaning]
random.shuffle(choices)
for i, btn in enumerate(choice_buttons):
if i < max_choices:
btn.config(text=choices[i], bg="SystemButtonFace", state="normal")
btn.grid()
else:
btn.grid_remove()
lbl_question.config(text=f"この単語の意味は? → 『{current_word}』")
lbl_result.config(text="")
# 回答チェック
def check_answer(i):
chosen = choices[i]
correct = words[current_word]['meaning']
if chosen == correct:
lbl_result.config(text="✅ 正解!", fg="green")
words[current_word]['correct'] += 1
else:
lbl_result.config(text=f"❌ 不正解。正解は『{correct}』です。", fg="red")
words[current_word]['wrong'] += 1
save_words(words)
for idx, btn in enumerate(choice_buttons):
if choices[idx] == correct:
btn.config(bg="lightgreen")
elif idx == i:
btn.config(bg="red")
for btn in choice_buttons:
btn.config(state="disabled")
# 結果表示&アプリ終了
def show_results_and_exit():
total_correct = sum(data.get('correct', 0) for data in words.values())
total_wrong = sum(data.get('wrong', 0) for data in words.values())
total = total_correct + total_wrong
rate = (total_correct / total * 100) if total > 0 else 0
messagebox.showinfo("終了", f"お疲れさまでした!\n正答率: {rate:.2f}%\n\nアプリを終了します。")
root.destroy()
# GUI構築
root = tk.Tk()
root.title("単語帳クイズアプリ")
lbl_question = tk.Label(root, text="問題がここに表示されます", font=("Arial", 18))
lbl_question.pack(pady=10)
frame_choices = tk.Frame(root)
frame_choices.pack()
choice_buttons = []
for i in range(4):
btn = tk.Button(frame_choices, text=f"選択肢{i+1}", width=20, command=lambda i=i: check_answer(i))
btn.grid(row=i//2, column=i%2, padx=5, pady=5)
choice_buttons.append(btn)
lbl_result = tk.Label(root, text="", font=("Arial", 14))
lbl_result.pack(pady=10)
btn_quiz = tk.Button(root, text="次の問題", command=quiz)
btn_quiz.pack(pady=10)
btn_exit = tk.Button(root, text="終了", fg="red", command=show_results_and_exit)
btn_exit.pack(pady=10)
quiz() # 最初の問題を表示
root.mainloop()
使い方
- 上記コードをコピーして
main.py
などの名前で保存します。 - 必要に応じて単語データを
initial_words
に追加してください。 - ターミナル(コマンドプロンプト)で
python main.py
を実行します。 - GUI画面が開くので、表示された英単語の意味を4択から選びます。
- 「次の問題」ボタンで問題を切り替え、終了したい時は「終了」ボタンを押します。
- 正答率が表示されてアプリが閉じます。
まとめ
- PythonとTkinterで簡単に単語クイズアプリを作れます。
- 問題データはJSONで保存し、正解・不正解の履歴も管理可能。
- GUIなので子どもや初心者でも使いやすい。
- 音声読み上げなしのため環境依存がなく安定動作。
気軽に単語学習をゲーム感覚で楽しみたい方におすすめです。
ぜひ自分の好きな単語を追加してカスタマイズしてみてくださいね!
質問や感想もお待ちしています!
最後まで読んでいただきありがとうございました😊