では、「メモ付き電卓(GUI版・フル機能)」として、以下の3機能を統合します:
1️⃣ 履歴をウィンドウ内に表示
2️⃣ 履歴から再計算ボタンで再利用
3️⃣ pandasで履歴を分析(平均・最大・最小など)
完成版:PySimpleGUI × pandas メモ付き電卓
import PySimpleGUI as sg
import pandas as pd
import datetime
import os
HISTORY_FILE = "calc_history.csv"
# --- 履歴をDataFrameで管理 ---
def load_history():
if os.path.exists(HISTORY_FILE):
return pd.read_csv(HISTORY_FILE)
else:
return pd.DataFrame(columns=["time", "expression", "result"])
def save_history(df):
df.to_csv(HISTORY_FILE, index=False, encoding="utf-8")
# --- pandasで集計 ---
def analyze_history(df):
if df.empty:
return "履歴がありません。"
try:
# 数値結果のみを抽出
numeric_results = pd.to_numeric(df["result"], errors="coerce").dropna()
if numeric_results.empty:
return "数値データがありません。"
return (
f"📊 履歴分析\n"
f"- 計算回数:{len(numeric_results)}回\n"
f"- 平均値:{numeric_results.mean():.3f}\n"
f"- 最大値:{numeric_results.max()}\n"
f"- 最小値:{numeric_results.min()}"
)
except Exception as e:
return f"分析エラー: {e}"
# --- 初期化 ---
df_history = load_history()
# --- GUI レイアウト ---
layout = [
[sg.Text("数式を入力してください(例:2+3*4)")],
[sg.Input(key="expr", size=(30, 1)), sg.Button("計算"), sg.Button("終了")],
[sg.Text("結果:", key="result", size=(40, 1), text_color="blue")],
[sg.HorizontalSeparator()],
[sg.Text("履歴一覧:")],
[sg.Table(
values=df_history.values.tolist(),
headings=["日時", "式", "結果"],
key="table",
enable_events=True,
auto_size_columns=False,
col_widths=[18, 15, 10],
justification="left",
num_rows=10
)],
[sg.Button("履歴から再計算"), sg.Button("分析を表示")],
[sg.Multiline(size=(45, 6), key="analysis", disabled=True, text_color="green")]
]
window = sg.Window("メモ付き電卓(分析付きGUI版)", layout, resizable=True)
# --- イベントループ ---
selected_row = None
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, "終了"):
break
if event == "計算":
expr = values["expr"]
if not expr.strip():
continue
try:
result = eval(expr)
window["result"].update(f"結果:{result}")
# 履歴に追加
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df_history.loc[len(df_history)] = [now, expr, result]
save_history(df_history)
window["table"].update(values=df_history.values.tolist())
window["expr"].update("") # 入力をクリア
except Exception as e:
sg.popup_error(f"エラー: {e}")
elif event == "table":
# 履歴表で選択された行を記録
selected_rows = values["table"]
if selected_rows:
selected_row = selected_rows[0]
selected_expr = df_history.iloc[selected_row]["expression"]
window["expr"].update(selected_expr)
elif event == "履歴から再計算":
if selected_row is not None:
expr = df_history.iloc[selected_row]["expression"]
try:
result = eval(expr)
window["result"].update(f"結果:{result}")
# 再計算も履歴に追記
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df_history.loc[len(df_history)] = [now, expr, result]
save_history(df_history)
window["table"].update(values=df_history.values.tolist())
except Exception as e:
sg.popup_error(f"エラー: {e}")
else:
sg.popup("再計算する式を履歴から選んでください。")
elif event == "分析を表示":
analysis_text = analyze_history(df_history)
window["analysis"].update(analysis_text)
window.close()
Python💡 機能まとめ
| 機能 | 説明 |
|---|---|
| リアルタイム履歴表示 | 計算結果がテーブルに即反映される |
| 履歴から再計算 | 過去の式をクリック→ボタンで再利用 |
| pandas分析 | 計算回数・平均・最大・最小を自動集計 |
| CSV保存 | calc_history.csv に履歴が保存される |
🖥️ 実行イメージ(概略)
数式を入力してください(例:2+3*4)
>>> 2+3*4
結果:14
履歴一覧:
日時 式 結果
2025-11-06 08:15 2+3*4 14
2025-11-06 08:16 (10-3)/2 3.5
📊 履歴分析
- 計算回数:2回
- 平均値:8.750
- 最大値:14
- 最小値:3.5
🔍 使い方のポイント
- 履歴クリック → 再計算ボタン で過去の式を再実行
- 分析ボタン で過去の計算を統計的にチェック
- CSVファイルはExcelでも開けます
- pandasが必要な場合は一度だけ:
pip install pandas PySimpleGUI
