レシピ管理アプリ
レシピの登録・検索・カテゴリ管理・材料リスト作成ができるアプリ。画像添付機能付きの本格的なDBアプリです。
1. アプリ概要
レシピの登録・検索・カテゴリ管理・材料リスト作成ができるアプリ。画像添付機能付きの本格的なDBアプリです。
このアプリは中級カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ)・Pillow で、難易度は ★★☆ です。
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+
インストールが必要なライブラリ
pip install pillow
4. 完全なソースコード
右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
5. コード解説
レシピ管理アプリのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App22クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
LabelFrameによるセクション分け
ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
Entryウィジェットとイベントバインド
ttk.Entryで入力フィールドを作成します。bind('
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
Textウィジェットでの結果表示
結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
例外処理とmessagebox
try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import sqlite3
import os
from datetime import datetime
try:
from PIL import Image, ImageTk
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
class App22:
"""レシピ管理アプリ"""
DB_PATH = os.path.join(os.path.dirname(__file__), "recipes.db")
CATEGORIES = ["和食", "洋食", "中華", "イタリアン", "デザート",
"サラダ", "スープ", "その他"]
def __init__(self, root):
self.root = root
self.root.title("レシピ管理アプリ")
self.root.geometry("960x620")
self.root.configure(bg="#fff8f0")
self._init_db()
self._build_ui()
self._load_recipes()
def _init_db(self):
self.conn = sqlite3.connect(self.DB_PATH)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category TEXT,
servings INTEGER DEFAULT 2,
prep_time INTEGER,
cook_time INTEGER,
ingredients TEXT,
steps TEXT,
notes TEXT,
image_path TEXT,
created_at TEXT
)
""")
self.conn.commit()
if not self.conn.execute("SELECT 1 FROM recipes").fetchone():
samples = [
("肉じゃが", "和食", 4, 10, 30,
"じゃがいも 4個\n玉ねぎ 1個\n牛肉 200g\nしょうゆ 大3\n砂糖 大2\nみりん 大2",
"1. じゃがいもを一口大に切る\n2. 玉ねぎを薄切りにする\n3. 油で肉を炒め野菜を加える\n4. 調味料と水を加えて20分煮る",
"じゃがいもが崩れる前に火を止める", ""),
("オムライス", "洋食", 2, 10, 15,
"卵 3個\nご飯 1膳\n鶏もも肉 100g\n玉ねぎ 1/4個\nケチャップ 大3\nバター 10g",
"1. 鶏肉と玉ねぎを炒める\n2. ご飯とケチャップを混ぜる\n3. 卵でご飯を包む",
"卵は半熟に仕上げる", ""),
]
for s in samples:
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,"
"cook_time,ingredients,steps,notes,image_path,created_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?)",
(*s, datetime.now().isoformat()))
self.conn.commit()
def _build_ui(self):
title_frame = tk.Frame(self.root, bg="#e65100", pady=10)
title_frame.pack(fill=tk.X)
tk.Label(title_frame, text="🍳 レシピ管理アプリ",
font=("Noto Sans JP", 15, "bold"),
bg="#e65100", fg="white").pack(side=tk.LEFT, padx=12)
# 検索バー
search_f = tk.Frame(self.root, bg="#fff3e0", pady=6)
search_f.pack(fill=tk.X)
tk.Label(search_f, text="🔍", bg="#fff3e0").pack(side=tk.LEFT, padx=8)
self.search_var = tk.StringVar()
ttk.Entry(search_f, textvariable=self.search_var, width=22).pack(
side=tk.LEFT, padx=4)
self.search_var.trace_add("write", lambda *a: self._load_recipes())
tk.Label(search_f, text="カテゴリ:", bg="#fff3e0").pack(side=tk.LEFT, padx=(12, 4))
self.cat_var = tk.StringVar(value="すべて")
cat_cb = ttk.Combobox(search_f, textvariable=self.cat_var,
values=["すべて"] + self.CATEGORIES,
state="readonly", width=12)
cat_cb.pack(side=tk.LEFT)
cat_cb.bind("<<ComboboxSelected>>", lambda e: self._load_recipes())
ttk.Button(search_f, text="🛒 材料リスト作成",
command=self._shopping_list).pack(side=tk.RIGHT, padx=8)
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
# 左: レシピ一覧
left = tk.Frame(paned, bg="#fff8f0")
cols = ("name", "category", "servings", "prep", "cook")
self.tree = ttk.Treeview(left, columns=cols,
show="headings", selectmode="browse")
for c, h, w in [("name", "レシピ名", 160), ("category", "カテゴリ", 80),
("servings", "人数", 50), ("prep", "下準備(分)", 70),
("cook", "調理時間(分)", 80)]:
self.tree.heading(c, text=h)
self.tree.column(c, width=w, minwidth=40)
sb = ttk.Scrollbar(left, command=self.tree.yview)
self.tree.configure(yscrollcommand=sb.set)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.pack(fill=tk.BOTH, expand=True)
self.tree.bind("<<TreeviewSelect>>", self._on_select)
paned.add(left, weight=1)
# 右: 詳細タブ
right = tk.Frame(paned, bg="#fff8f0")
self.notebook = ttk.Notebook(right)
self.notebook.pack(fill=tk.BOTH, expand=True)
# レシピ詳細タブ
detail_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(detail_tab, text="レシピ詳細")
self._build_detail_tab(detail_tab)
# 編集タブ
edit_tab = tk.Frame(self.notebook, bg="#fff8f0")
self.notebook.add(edit_tab, text="編集")
self._build_edit_tab(edit_tab)
paned.add(right, weight=2)
self.status_var = tk.StringVar(value="")
tk.Label(self.root, textvariable=self.status_var,
bg="#ffe0b2", font=("Arial", 9), anchor="w", padx=8
).pack(fill=tk.X, side=tk.BOTTOM)
self._selected_id = None
def _build_detail_tab(self, parent):
self.detail_name = tk.Label(parent, text="",
font=("Noto Sans JP", 14, "bold"),
bg="#fff8f0", fg="#e65100")
self.detail_name.pack(anchor="w", padx=8, pady=4)
info_f = tk.Frame(parent, bg="#fff8f0")
info_f.pack(fill=tk.X, padx=8)
self.detail_info = tk.Label(info_f, text="",
bg="#fff8f0", fg="#555",
font=("Arial", 10))
self.detail_info.pack(side=tk.LEFT)
# 画像
self.img_label = tk.Label(parent, bg="#fff8f0", text="")
self.img_label.pack(anchor="w", padx=8)
inner = ttk.PanedWindow(parent, orient=tk.HORIZONTAL)
inner.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
ing_f = ttk.LabelFrame(inner, text="材料", padding=6)
self.ing_text = tk.Text(ing_f, width=20, font=("Noto Sans JP", 10),
bg="#fffde7", relief=tk.FLAT, state=tk.DISABLED)
self.ing_text.pack(fill=tk.BOTH, expand=True)
inner.add(ing_f, weight=1)
step_f = ttk.LabelFrame(inner, text="手順", padding=6)
self.step_text = tk.Text(step_f, width=32, font=("Noto Sans JP", 10),
bg="#f1f8e9", relief=tk.FLAT, state=tk.DISABLED,
wrap=tk.WORD)
self.step_text.pack(fill=tk.BOTH, expand=True)
inner.add(step_f, weight=2)
def _build_edit_tab(self, parent):
f = tk.Frame(parent, bg="#fff8f0")
f.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
for row, (lbl, attr) in enumerate([("レシピ名", "ename"),
("カテゴリ", None),
("人数", "eservings"),
("下準備(分)", "eprep"),
("調理時間(分)", "ecook"),
("画像パス", "eimg")]):
tk.Label(f, text=f"{lbl}:", bg="#fff8f0").grid(
row=row, column=0, sticky="w", pady=3)
if lbl == "カテゴリ":
self.ecat_var = tk.StringVar(value=self.CATEGORIES[0])
ttk.Combobox(f, textvariable=self.ecat_var,
values=self.CATEGORIES, state="readonly",
width=14).grid(row=row, column=1, padx=4, sticky="w")
else:
var = tk.StringVar()
ttk.Entry(f, textvariable=var, width=22).grid(
row=row, column=1, padx=4, sticky="w")
setattr(self, f"{attr}_var", var)
ttk.Button(f, text="📷 画像選択",
command=self._pick_image).grid(
row=len([0]*6), column=2, padx=4)
tk.Label(f, text="材料:", bg="#fff8f0").grid(
row=7, column=0, sticky="nw", pady=3)
self.eing_text = tk.Text(f, height=4, width=30, font=("Arial", 10))
self.eing_text.grid(row=7, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="手順:", bg="#fff8f0").grid(
row=8, column=0, sticky="nw", pady=3)
self.estep_text = tk.Text(f, height=5, width=30, font=("Arial", 10))
self.estep_text.grid(row=8, column=1, columnspan=2, padx=4, pady=2)
tk.Label(f, text="メモ:", bg="#fff8f0").grid(
row=9, column=0, sticky="nw", pady=3)
self.enotes_text = tk.Text(f, height=2, width=30, font=("Arial", 10))
self.enotes_text.grid(row=9, column=1, columnspan=2, padx=4, pady=2)
btn_f = tk.Frame(f, bg="#fff8f0")
btn_f.grid(row=10, column=0, columnspan=3, pady=6)
for text, cmd in [("➕ 追加", self._add_recipe),
("✏️ 更新", self._update_recipe),
("🗑️ 削除", self._delete_recipe)]:
ttk.Button(btn_f, text=text, command=cmd).pack(side=tk.LEFT, padx=4)
def _load_recipes(self):
q = self.search_var.get().lower()
cat = self.cat_var.get()
sql = ("SELECT id,name,category,servings,prep_time,cook_time "
"FROM recipes WHERE 1=1")
params = []
if q:
sql += " AND LOWER(name) LIKE ?"
params.append(f"%{q}%")
if cat != "すべて":
sql += " AND category=?"
params.append(cat)
sql += " ORDER BY name"
rows = self.conn.execute(sql, params).fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
rid, name, category, srv, prep, cook = row
self.tree.insert("", "end", iid=str(rid),
values=(name, category, srv, prep or "", cook or ""))
self.status_var.set(f"{len(rows)} 件")
def _on_select(self, event):
sel = self.tree.selection()
if not sel:
return
rid = int(sel[0])
self._selected_id = rid
row = self.conn.execute(
"SELECT name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path FROM recipes WHERE id=?",
(rid,)).fetchone()
if not row:
return
(name, cat, srv, prep, cook, ing, steps, notes, img_path) = row
# 詳細タブ更新
self.detail_name.config(text=name)
self.detail_info.config(
text=f"📂 {cat} 👥 {srv}人前 ⏱ 下{prep or '-'}分 / 調{cook or '-'}分"
+ (f"\n📝 {notes}" if notes else ""))
for txt, content in [(self.ing_text, ing or ""),
(self.step_text, steps or "")]:
txt.config(state=tk.NORMAL)
txt.delete("1.0", tk.END)
txt.insert("1.0", content)
txt.config(state=tk.DISABLED)
# 画像
if PIL_AVAILABLE and img_path and os.path.exists(img_path):
try:
img = Image.open(img_path).resize((200, 150), Image.LANCZOS)
self._photo = ImageTk.PhotoImage(img)
self.img_label.config(image=self._photo)
except Exception:
self.img_label.config(image="")
else:
self.img_label.config(image="")
# 編集タブ更新
self.ename_var.set(name)
self.ecat_var.set(cat or self.CATEGORIES[0])
self.eservings_var.set(str(srv))
self.eprep_var.set(str(prep or ""))
self.ecook_var.set(str(cook or ""))
self.eimg_var.set(img_path or "")
self.eing_text.delete("1.0", tk.END)
self.eing_text.insert("1.0", ing or "")
self.estep_text.delete("1.0", tk.END)
self.estep_text.insert("1.0", steps or "")
self.enotes_text.delete("1.0", tk.END)
self.enotes_text.insert("1.0", notes or "")
def _add_recipe(self):
name = self.ename_var.get().strip()
if not name:
messagebox.showwarning("警告", "レシピ名を入力してください")
return
self.conn.execute(
"INSERT INTO recipes (name,category,servings,prep_time,cook_time,"
"ingredients,steps,notes,image_path,created_at) VALUES "
"(?,?,?,?,?,?,?,?,?,?)",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(),
datetime.now().isoformat()))
self.conn.commit()
self._load_recipes()
def _update_recipe(self):
if not self._selected_id:
return
name = self.ename_var.get().strip()
if not name:
return
self.conn.execute(
"UPDATE recipes SET name=?,category=?,servings=?,prep_time=?,"
"cook_time=?,ingredients=?,steps=?,notes=?,image_path=? WHERE id=?",
(name, self.ecat_var.get(),
int(self.eservings_var.get() or 2),
int(self.eprep_var.get() or 0),
int(self.ecook_var.get() or 0),
self.eing_text.get("1.0", tk.END).strip(),
self.estep_text.get("1.0", tk.END).strip(),
self.enotes_text.get("1.0", tk.END).strip(),
self.eimg_var.get(), self._selected_id))
self.conn.commit()
self._load_recipes()
def _delete_recipe(self):
if not self._selected_id:
return
if messagebox.askyesno("確認", "このレシピを削除しますか?"):
self.conn.execute("DELETE FROM recipes WHERE id=?",
(self._selected_id,))
self.conn.commit()
self._selected_id = None
self._load_recipes()
def _pick_image(self):
path = filedialog.askopenfilename(
filetypes=[("画像", "*.jpg *.jpeg *.png *.bmp"),
("すべて", "*.*")])
if path:
self.eimg_var.set(path)
def _shopping_list(self):
"""選択中のレシピの材料リストを表示"""
if not self._selected_id:
messagebox.showinfo("情報", "レシピを選択してください")
return
ing = self.conn.execute(
"SELECT ingredients FROM recipes WHERE id=?",
(self._selected_id,)).fetchone()
if not ing or not ing[0]:
return
win = tk.Toplevel(self.root)
win.title("🛒 材料リスト")
win.geometry("300x300")
txt = tk.Text(win, font=("Noto Sans JP", 11), wrap=tk.WORD)
txt.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)
txt.insert("1.0", "【材料リスト】\n\n" + ing[0])
txt.config(state=tk.DISABLED)
if __name__ == "__main__":
root = tk.Tk()
app = App22(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app22.py と保存します。
-
2クラスの骨格を作る
App22クラスを定義し、__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モジュールを使います。