素数チェッカー
入力した数が素数かどうか判定するアプリ。エラトステネスの篩アルゴリズムの実装を学びます。
1. アプリ概要
入力した数が素数かどうか判定するアプリ。エラトステネスの篩アルゴリズムの実装を学びます。
このアプリはツールカテゴリに分類される実践的な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 math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
5. コード解説
素数チェッカーのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App32クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox
import math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox
import math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox
import math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox
import math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox
import math
class App32:
"""素数チェッカー"""
def __init__(self, root):
self.root = root
self.root.title("素数チェッカー")
self.root.geometry("480x420")
self.root.configure(bg="#f8f9fc")
self._build_ui()
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=20, pady=16)
main_frame.pack(fill=tk.BOTH, expand=True)
# 素数判定
check_frame = ttk.LabelFrame(main_frame, text="素数判定", padding=10)
check_frame.pack(fill=tk.X, pady=(0, 10))
tk.Label(check_frame, text="数を入力:").grid(row=0, column=0, sticky="w")
self.check_entry = ttk.Entry(check_frame, width=16, font=("Arial", 13))
self.check_entry.grid(row=0, column=1, padx=8, sticky="ew")
self.check_entry.bind("<Return>", lambda e: self.check_prime())
ttk.Button(check_frame, text="判定", command=self.check_prime).grid(
row=0, column=2, padx=4)
check_frame.columnconfigure(1, weight=1)
self.check_result = tk.Label(main_frame, text="",
bg="#f8f9fc", font=("Noto Sans JP", 14, "bold"))
self.check_result.pack(pady=(0, 8))
# 素数一覧
list_frame = ttk.LabelFrame(main_frame, text="素数一覧(N以下)", padding=10)
list_frame.pack(fill=tk.BOTH, expand=True)
ctrl = tk.Frame(list_frame, bg=list_frame.cget("bg"))
ctrl.pack(fill=tk.X, pady=(0, 6))
tk.Label(ctrl, text="上限:", bg=list_frame.cget("bg")).pack(side=tk.LEFT)
self.limit_var = tk.IntVar(value=100)
ttk.Spinbox(ctrl, from_=10, to=10000, textvariable=self.limit_var,
width=8, font=("Arial", 11)).pack(side=tk.LEFT, padx=6)
ttk.Button(ctrl, text="一覧表示", command=self.list_primes).pack(side=tk.LEFT)
self.list_text = tk.Text(list_frame, font=("Courier New", 11),
bg="white", relief=tk.FLAT, state=tk.DISABLED, height=8)
self.list_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(list_frame, command=self.list_text.yview)
self.list_text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
def is_prime(self, n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def check_prime(self):
text = self.check_entry.get().strip()
try:
n = int(text)
except ValueError:
messagebox.showerror("エラー", "整数を入力してください")
return
if self.is_prime(n):
self.check_result.config(text=f"✅ {n} は素数です", fg="#27ae60")
else:
self.check_result.config(text=f"❌ {n} は素数ではありません", fg="#e74c3c")
def list_primes(self):
limit = self.limit_var.get()
primes = [i for i in range(2, limit + 1) if self.is_prime(i)]
lines = [f"2〜{limit} の素数一覧({len(primes)}個)\n"]
# 10個ずつ表示
for i in range(0, len(primes), 10):
row = primes[i:i+10]
lines.append(" " + " ".join(f"{p:5d}" for p in row))
self.list_text.config(state=tk.NORMAL)
self.list_text.delete("1.0", tk.END)
self.list_text.insert("1.0", "\n".join(lines))
self.list_text.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App32(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app32.py と保存します。
-
2クラスの骨格を作る
App32クラスを定義し、__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モジュールを使います。