クイズタイマー
残り時間をカウントダウンして問題を出すタイマークイズ。Progressbarウィジェットの活用を学びます。
1. アプリ概要
残り時間をカウントダウンして問題を出すタイマークイズ。Progressbarウィジェットの活用を学びます。
このアプリはゲームカテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ) で、難易度は ★★☆ です。
Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。
ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。
GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。
2. 機能一覧
- クイズタイマーのメイン機能
- 直感的なGUIインターフェース
- 入力値のバリデーション
- エラーハンドリング
- 結果の見やすい表示
- キーボードショートカット対応
3. 事前準備・環境
Python 3.10 以上 / Windows・Mac・Linux すべて対応
以下の環境で動作確認しています。
- Python 3.10 以上
- OS: Windows 10/11・macOS 12+・Ubuntu 20.04+
4. 完全なソースコード
右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
5. コード解説
クイズタイマーのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App36クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox
import random
class App36:
"""クイズタイマー"""
QUESTIONS = [
{"q": "Pythonの生みの親は?", "a": "グイド・ヴァンロッサム"},
{"q": "Python 3のprint()はメソッドか関数か?", "a": "関数"},
{"q": "リストのソートメソッドは?", "a": "sort()"},
{"q": "Noneの型は?", "a": "NoneType"},
{"q": "辞書のキーと値を同時に取り出すメソッドは?", "a": "items()"},
{"q": "文字列を整数に変換する関数は?", "a": "int()"},
{"q": "Pythonのインデントは何のために使う?", "a": "コードブロックの区切り"},
{"q": "例外処理に使うキーワードは?", "a": "try / except"},
{"q": "クラスの初期化メソッドの名前は?", "a": "__init__"},
{"q": "lambdaは何を定義する?", "a": "無名関数(ラムダ関数)"},
]
def __init__(self, root):
self.root = root
self.root.title("クイズタイマー")
self.root.geometry("500x440")
self.root.configure(bg="#f8f9fc")
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
self.time_limit = 15 # 秒
self.remaining = self.time_limit
self._after_id = None
self._build_ui()
self._load_question()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="クイズタイマー",
font=("Noto Sans JP", 16, "bold"),
bg="#3776ab", fg="white").pack()
main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=24, pady=14)
main_frame.pack(fill=tk.BOTH, expand=True)
# 進捗とタイマー
top_row = tk.Frame(main_frame, bg="#f8f9fc")
top_row.pack(fill=tk.X, pady=(0, 8))
self.progress_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 11), fg="#666")
self.progress_label.pack(side=tk.LEFT)
self.timer_label = tk.Label(top_row, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"), fg="#e74c3c")
self.timer_label.pack(side=tk.RIGHT)
self.timer_bar = ttk.Progressbar(main_frame, maximum=self.time_limit,
mode="determinate", length=440)
self.timer_bar.pack(fill=tk.X, pady=(0, 12))
# 問題
self.question_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 14, "bold"),
wraplength=440, justify="left")
self.question_label.pack(anchor="w", pady=(0, 14))
# 回答入力
tk.Label(main_frame, text="答え:", bg="#f8f9fc",
font=("Noto Sans JP", 11)).pack(anchor="w")
self.answer_entry = ttk.Entry(main_frame, font=("Noto Sans JP", 13), width=30)
self.answer_entry.pack(anchor="w", pady=(4, 10))
self.answer_entry.bind("<Return>", lambda e: self.submit())
btn_row = tk.Frame(main_frame, bg="#f8f9fc")
btn_row.pack()
ttk.Button(btn_row, text="回答する", command=self.submit).pack(side=tk.LEFT, padx=6)
ttk.Button(btn_row, text="スキップ", command=self.skip).pack(side=tk.LEFT, padx=6)
self.feedback_label = tk.Label(main_frame, text="", bg="#f8f9fc",
font=("Noto Sans JP", 12, "bold"))
self.feedback_label.pack(pady=8)
def _load_question(self):
if self._after_id:
self.root.after_cancel(self._after_id)
self.remaining = self.time_limit
q = self.questions[self.current]
self.question_label.config(
text=f"Q{self.current+1}. {q['q']}")
self.progress_label.config(
text=f"{self.current+1} / {len(self.questions)}")
self.answer_entry.delete(0, tk.END)
self.answer_entry.config(state=tk.NORMAL)
self.feedback_label.config(text="")
self._tick()
def _tick(self):
self.timer_label.config(text=f"⏳ {self.remaining}秒")
self.timer_bar["value"] = self.remaining
if self.remaining <= 5:
self.timer_label.config(fg="#e74c3c")
else:
self.timer_label.config(fg="#3776ab")
if self.remaining <= 0:
self.feedback_label.config(
text=f"⏰ 時間切れ!正解: {self.questions[self.current]['a']}",
fg="#e74c3c")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(2000, self.next_question)
return
self.remaining -= 1
self._after_id = self.root.after(1000, self._tick)
def submit(self):
if self.answer_entry.cget("state") == tk.DISABLED:
return
answer = self.answer_entry.get().strip()
correct = self.questions[self.current]["a"]
if self._after_id:
self.root.after_cancel(self._after_id)
self.answer_entry.config(state=tk.DISABLED)
if answer == correct or answer.lower() == correct.lower():
self.score += 1
self.feedback_label.config(text="✅ 正解!", fg="#27ae60")
else:
self.feedback_label.config(
text=f"❌ 不正解。正解: {correct}", fg="#e74c3c")
self.root.after(1800, self.next_question)
def skip(self):
if self._after_id:
self.root.after_cancel(self._after_id)
correct = self.questions[self.current]["a"]
self.feedback_label.config(text=f"→ スキップ。正解: {correct}", fg="#888")
self.answer_entry.config(state=tk.DISABLED)
self.root.after(1500, self.next_question)
def next_question(self):
self.current += 1
if self.current >= len(self.questions):
self._show_result()
else:
self._load_question()
def _show_result(self):
if self._after_id:
self.root.after_cancel(self._after_id)
for w in self.root.winfo_children():
w.destroy()
frame = tk.Frame(self.root, bg="#f8f9fc")
frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
total = len(self.questions)
tk.Label(frame, text="クイズ終了!", font=("Noto Sans JP", 20, "bold"),
bg="#f8f9fc").pack(pady=(0, 16))
tk.Label(frame, text=f"スコア: {self.score} / {total}",
font=("Noto Sans JP", 22, "bold"), bg="#f8f9fc",
fg="#3776ab").pack()
pct = self.score / total * 100
msg = "完璧!" if pct == 100 else "素晴らしい!" if pct >= 80 else "良い挑戦!" if pct >= 60 else "次は頑張ろう!"
tk.Label(frame, text=msg, font=("Noto Sans JP", 13),
bg="#f8f9fc").pack(pady=10)
ttk.Button(frame, text="もう一度", command=self._restart).pack(pady=16)
def _restart(self):
self.questions = random.sample(self.QUESTIONS, len(self.QUESTIONS))
self.current = 0
self.score = 0
for w in self.root.winfo_children():
w.destroy()
self._build_ui()
self._load_question()
if __name__ == "__main__":
root = tk.Tk()
app = App36(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app36.py と保存します。
-
2クラスの骨格を作る
App36クラスを定義し、__init__とmainloop()の最小構成を作ります。
-
3タイトルバーを作る
Frameを使ってカラーバー付きのタイトルエリアを作ります。
-
4入力フォームを実装する
LabelFrameとEntryウィジェットで入力エリアを作ります。
-
5処理ロジックを実装する
_calculate()メソッドに計算・処理ロジックを実装します。
-
6結果表示を実装する
TextウィジェットかLabelに結果を表示する_show_result()を実装します。
-
7エラー処理を追加する
try-exceptとmessageboxでエラーハンドリングを追加します。
7. カスタマイズアイデア
基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。
💡 ダークモードを追加する
bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。
💡 データのエクスポート機能
計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。
💡 入力履歴機能
以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。
8. よくある問題と解決法
❌ 日本語フォントが表示されない
原因:システムに日本語フォントが見つからない場合があります。
解決法:font引数を省略するかシステムに合ったフォントを指定してください。
❌ ウィンドウのサイズが変更できない
原因:resizable(False, False)が設定されています。
解決法:resizable(True, True)に変更してください。
9. 練習問題
アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。
-
課題1:機能拡張
クイズタイマーに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。
-
課題2:UIの改善
色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。
-
課題3:保存機能の追加
入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。