0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

まだExcelを使いますか? -- FlexiCalc --

0
Last updated at Posted at 2026-04-04

これまでにも!

バイブコーディングで作った作品をご紹介してきました!!
コレ以前もありますが、結構使えつアプリケーションとして
無料のGeminiでLinuxのGUIアプリを作った話
この記事では画像とともに保存できるメモプログラムを作りました。

役立つPythonプログラム(見積書作成システム)
ここでは、GUIで入力して見積書をPDFで出力、保存・読込ができるツールを作りました。

今回は、計算機です。
電卓はもういらないです、一度立てた式を再利用できる電卓として
FlexiCalcというコマンドを作りました。

動作環境

Tkinterと関数計算にmathライブラリを使っているだけなのでインストール直後の環境で何もせずに動くはずです。
Linuxの場合はTkinterを入れないとだめですけどね。

ソース

例のごとくコマンドとして動かすのでシバンを使っています。ファイル名はFlexiCalcで保存し
chmod +x FlexCalc で実行権をつけてくださ。

#!/usr/bin/env python3
import tkinter as tk
from tkinter import messagebox, filedialog, ttk
import re
import json
import math

class FlexiCalc:
    def __init__(self, root):
        self.root = root
        self.root.title("FlexiCalc - 動的数式計算機")
        self.root.geometry("500x650")

        # --- 上部:固定エリア ---
        top_frame = tk.Frame(root)
        top_frame.pack(fill=tk.X, pady=5)
        
        # ヘルプボタンを右上に配置
        help_btn = tk.Button(top_frame, text="?", width=3, command=self.show_help, bg="#f0f0f0")
        help_btn.pack(side=tk.RIGHT, padx=10)

        tk.Label(top_frame, text="数式を入力:").pack()
        self.formula_entry = tk.Entry(top_frame, width=45)
        self.formula_entry.pack(pady=5, padx=20)
        
        self.gen_button = tk.Button(top_frame, text="入力枠を生成", command=self.generate_inputs)
        self.gen_button.pack(pady=5)

        # --- 中部:スクロールエリア (前回と同じ) ---
        container = tk.Frame(root)
        container.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        self.canvas = tk.Canvas(container)
        scrollbar = ttk.Scrollbar(container, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = tk.Frame(self.canvas)

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )

        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=scrollbar.set)
        self.canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # マウスホイール設定
        self.canvas.bind_all("<Button-4>", lambda e: self.canvas.yview_scroll(-1, "units"))
        self.canvas.bind_all("<Button-5>", lambda e: self.canvas.yview_scroll(1, "units"))

        # --- 下部:操作エリア ---
        bottom_frame = tk.Frame(root)
        bottom_frame.pack(fill=tk.X, pady=10)

        self.calc_button = tk.Button(bottom_frame, text="計算実行", command=self.calculate, state=tk.DISABLED, bg="#4CAF50", fg="white", width=20)
        self.calc_button.pack(pady=5)

        self.result_label = tk.Label(bottom_frame, text="結果: ", font=("Arial", 12, "bold"))
        self.result_label.pack(pady=10)

        btn_frame = tk.Frame(bottom_frame)
        btn_frame.pack(pady=5)
        tk.Button(btn_frame, text="JSON保存", command=self.save_data).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="JSON読込", command=self.load_data).pack(side=tk.LEFT, padx=5)

        self.inputs = {}

    def show_help(self):
        """使い方の例を表示する"""
        help_text = """【FlexiCalc 使い方ガイド】

1. 数式を入力する
   一番上のボックスに計算したい式を入れます。
   例: (A + B) * C / 100
   例: sqrt(x**2 + y**2)  <- 三平方の定理

2. 入力枠を生成する
   「入力枠を生成」を押すと、式の中の変数名(A, B, x など)が
   自動でリストアップされ、数値入力欄が作られます。

3. 計算する
   各欄に数値を入力し、「計算実行」を押します。

【使える関数・定数の例】
・pi (円周率), e (ネイピア数)
・sin(x), cos(x), tan(x) ※ラジアン指定
・sqrt(x) (平方根), log(x) (自然対数)
・pow(x, y) または x**y (べき乗)

【便利なTips】
・保存機能を使えば、複雑なパラメータ設定をいつでも復元できます。
・Ubuntu環境では、マウスホイールで入力欄をスクロールできます。
        """
        messagebox.showinfo("FlexiCalc ヘルプ", help_text)

    def generate_inputs(self):
        formula = self.formula_entry.get()
        words = re.findall(r'[a-zA-Z_]\w*', formula)
        variables = sorted(list(set([w for w in words if w not in dir(math) and w not in ["pi", "e"]])))

        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        self.inputs = {}

        for var in variables:
            row = tk.Frame(self.scrollable_frame)
            row.pack(fill=tk.X, pady=2)
            tk.Label(row, text=f"{var} :", width=10, anchor="e").pack(side=tk.LEFT, padx=5)
            entry = tk.Entry(row)
            entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
            self.inputs[var] = entry

        self.calc_button.config(state=tk.NORMAL if (variables or words or formula) else tk.DISABLED)

    def calculate(self):
        formula = self.formula_entry.get()
        try:
            context = {var: float(entry.get()) for var, entry in self.inputs.items()}
            calc_env = {**math.__dict__, **context}
            calc_env["__builtins__"] = None
            result = eval(formula, calc_env)
            self.result_label.config(text=f"結果: {result}")
        except Exception as e:
            messagebox.showerror("エラー", f"計算失敗: {e}")

    def save_data(self):
        data = {"formula": self.formula_entry.get(), "values": {var: entry.get() for var, entry in self.inputs.items()}}
        file_path = filedialog.asksaveasfilename(defaultextension=".json", initialfile="flexicalc_save.json")
        if file_path:
            with open(file_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=4)

    def load_data(self):
        file_path = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
        if not file_path: return
        with open(file_path, "r") as f: data = json.load(f)
        self.formula_entry.delete(0, tk.END)
        self.formula_entry.insert(0, data.get("formula", ""))
        self.generate_inputs()
        for var, val in data.get("values", {}).items():
            if var in self.inputs: self.inputs[var].insert(0, val)

if __name__ == "__main__":
    root = tk.Tk()
    app = FlexiCalc(root)
    root.mainloop()

このプログラムでは、計算内容と結果をJsonで保存し復元できます。
1度立てた式を無駄にしない、だれかと計算方法を共有したいときにも役立ちます。

このようにJson形式は自由にデータの形を決められるので見積書でも利用しています。

バイブコーディングでExcelはもう不要

このように帳票系ドキュメントの作成にせよ計算にせよPythonをツールとして使いバイブコーディングすればExcelはもう不要です。

詳しくお知りになりたい方は、m_kawase@embed-ai.comまでご連絡下さいませ。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?