メモ帳アプリ
テキストの入力・保存・読み込みができるシンプルなメモ帳。ファイルI/Oの実践的な使い方を学びます。
1. アプリ概要
テキストの入力・保存・読み込みができるシンプルなメモ帳。ファイルI/Oの実践的な使い方を学びます。
このアプリはツールカテゴリに分類される実践的な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, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
5. コード解説
メモ帳アプリのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App21クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import os
class App21:
"""メモ帳アプリ"""
def __init__(self, root):
self.root = root
self.root.title("メモ帳 - 無題")
self.root.geometry("540x440")
self.root.configure(bg="#f8f9fc")
self.current_file = None
self.modified = False
self._build_ui()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#3776ab", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="メモ帳アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#3776ab", fg="white").pack()
# ツールバー
toolbar = tk.Frame(self.root, bg="#e8eaf0", pady=4)
toolbar.pack(fill=tk.X)
for label, cmd in [("📄 新規", self.new_file), ("📂 開く", self.open_file),
("💾 保存", self.save_file), ("💾 名前を付けて保存", self.save_as)]:
ttk.Button(toolbar, text=label, command=cmd).pack(side=tk.LEFT, padx=3)
# テキストエリア
text_frame = tk.Frame(self.root)
text_frame.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
self.text = tk.Text(text_frame, font=("Courier New", 12), wrap=tk.WORD,
undo=True, bg="white", fg="#111",
insertbackground="#3776ab", padx=8, pady=8)
self.text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
sb = ttk.Scrollbar(text_frame, command=self.text.yview)
self.text.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
# ステータスバー
self.status_var = tk.StringVar(value="行: 1 列: 1 文字数: 0")
tk.Label(self.root, textvariable=self.status_var, anchor="w",
bg="#e8eaf0", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
self.text.bind("<KeyRelease>", self._on_change)
self.root.bind("<Control-n>", lambda e: self.new_file())
self.root.bind("<Control-o>", lambda e: self.open_file())
self.root.bind("<Control-s>", lambda e: self.save_file())
def _on_change(self, event=None):
self.modified = True
pos = self.text.index(tk.INSERT)
line, col = pos.split(".")
chars = len(self.text.get("1.0", tk.END)) - 1
self.status_var.set(f"行: {line} 列: {int(col)+1} 文字数: {chars}")
def new_file(self):
if self.modified and self.text.get("1.0", tk.END).strip():
if not messagebox.askyesno("確認", "変更を破棄して新規作成しますか?"):
return
self.text.delete("1.0", tk.END)
self.current_file = None
self.modified = False
self.root.title("メモ帳 - 無題")
def open_file(self):
path = filedialog.askopenfilename(
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, encoding="utf-8") as f:
self.text.delete("1.0", tk.END)
self.text.insert("1.0", f.read())
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
def save_file(self):
if self.current_file:
with open(self.current_file, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.modified = False
else:
self.save_as()
def save_as(self):
path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("テキストファイル", "*.txt"), ("全てのファイル", "*.*")])
if not path:
return
with open(path, "w", encoding="utf-8") as f:
f.write(self.text.get("1.0", tk.END))
self.current_file = path
self.modified = False
self.root.title(f"メモ帳 - {os.path.basename(path)}")
if __name__ == "__main__":
root = tk.Tk()
app = App21(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app21.py と保存します。
-
2クラスの骨格を作る
App21クラスを定義し、__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モジュールを使います。