In this tutorial, we’ll create InsurePredict v1.0, a GUI application to predict insurance costs using Python. We’ll use Tkinter, ttkbootstrap, and scikit-learn for AI-driven predictions. By the end, you’ll have a smooth, multi-file, drag & drop GUI app.
- Setup & Install Dependencies
First, make sure you have Python 3.10+ installed. Then, install the required packages:
pip install pandas scikit-learn ttkbootstrap
If you want drag & drop support:
pip install tkinterdnd2
Tip: tkinterdnd2 is optional. Without it, you can still browse CSV files normally.
- Create the App Header
We’ll start by defining the app name and version. This will be displayed at the top of the GUI.
APP_NAME = "InsurePredict"
APP_VERSION = "1.0"
print(f"{APP_NAME} v{APP_VERSION} - Insurance Cost Prediction Tool")
This is just a placeholder to show the app’s info. Later, it will appear in the GUI.
- Import Necessary Libraries
We’ll need GUI, threading, and data libraries:
import os
import sys
import threading
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas as pd
from sklearn.linear_model import LinearRegression
import ttkbootstrap as tb
from ttkbootstrap.constants import *
ttkbootstrap is used to make the GUI look modern with themes.
- Optional: Enable Drag & Drop
If you installed tkinterdnd2, enable drag & drop support:
try:
from tkinterdnd2 import TkinterDnD, DND_FILES
DND_ENABLED = True
except ImportError:
DND_ENABLED = False
print("Drag & Drop requires tkinterdnd2. Install via pip install tkinterdnd2")
- Prediction Worker
We’ll create a PredictionWorker class that handles predictions in a separate thread, keeping the GUI responsive:
class PredictionWorker:
def __init__(self, files, callbacks):
self.files = files
self.callbacks = callbacks
self._running = True
self.model = LinearRegression()
# Example training with sample data
self.model.fit([[18,0],[25,1],[40,1],[60,0]], [2000,3000,4000,3500])
def stop(self):
self._running = False
def run(self):
results = []
for i, file in enumerate(self.files):
if not self._running:
break
try:
df = pd.read_csv(file)
if "age" in df.columns and "smoker" in df.columns:
pred = self.model.predict(df[["age","smoker"]])
results.append((file, pred.tolist()))
else:
results.append((file, "Missing columns"))
except Exception as e:
results.append((file, f"Error: {e}"))
if "progress" in self.callbacks:
self.callbacks["progress"](int((i+1)/len(self.files)*100))
if "found" in self.callbacks:
self.callbacks["found"](file, results[-1][1])
if "finished" in self.callbacks:
self.callbacks["finished"]()
Explanation:
We train a dummy LinearRegression model on sample data.
The worker reads CSV files, predicts insurance costs, and sends progress back to the GUI.
- Build the Main GUI
Now let’s start the main app class with Tkinter and ttkbootstrap:
class InsurePredictApp:
def __init__(self):
if DND_ENABLED:
self.root = TkinterDnD.Tk()
else:
self.root = tb.Window(themename="darkly")
self.root.title(f"{APP_NAME} v{APP_VERSION}")
self.root.minsize(1000, 600)
self.file_set = set()
self._build_ui()
- GUI Layout
We add a file input, buttons, progress bar, and a treeview for predictions:
def _build_ui(self):
main = tb.Frame(self.root, padding=10)
main.pack(fill=tk.BOTH, expand=True)
tb.Label(main, text=f"💰 {APP_NAME} - Insurance Cost Predictor",
font=("Segoe UI", 22, "bold")).pack(pady=(0,4))
# File input row
row1 = tb.Frame(main)
row1.pack(fill=tk.X, pady=(0,6))
self.path_input = tb.Entry(row1, width=80)
self.path_input.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.path_input.insert(0, "Drag & drop CSV files here…")
browse_btn = tb.Button(row1, text="📂 Browse", bootstyle=INFO, command=self.browse)
browse_btn.pack(side=tk.LEFT, padx=3)
self.start_btn = tb.Button(row1, text="🚀 Predict", bootstyle=SUCCESS, command=self.start)
self.start_btn.pack(side=tk.LEFT, padx=3)
# Progress bar
self.progress = tb.Progressbar(main, bootstyle="success-striped", maximum=100)
self.progress.pack(fill=tk.X, pady=(0,6))
# Treeview for results
self.tree = ttk.Treeview(main, columns=("selected","filename","prediction"), show="headings")
self.tree.heading("selected", text="✅")
self.tree.heading("filename", text="Filename")
self.tree.heading("prediction", text="Prediction")
self.tree.pack(fill=tk.BOTH, expand=True)
This layout gives users a simple drag & drop or browse interface with a progress bar and a results table.
- File Selection Functions
Handle browsing and dropping CSV files:
def browse(self):
files = filedialog.askopenfilenames(filetypes=[("CSV Files","*.csv")])
if files:
self._insert_files(files)
def _insert_files(self, paths):
for path in paths:
if path.endswith(".csv") and path not in self.file_set:
self.file_set.add(path)
self.tree.insert("", tk.END, values=("☑️", path, "Queued"))
- Run Predictions
Start the prediction worker when the user clicks “Predict”:
def start(self):
selected_files = [self.tree.item(i)['values'][1] for i in self.tree.get_children() if self.tree.item(i)['values'][0]=="☑️"]
if not selected_files:
messagebox.showwarning("No Selection", "Select CSV files first.")
return
threading.Thread(target=self._run_worker, args=(selected_files,), daemon=True).start()
def _run_worker(self, files):
self.worker_obj = PredictionWorker(files, callbacks={
"found": self.add_prediction,
"progress": self.set_target,
"finished": self.finish
})
self.worker_obj.run()
- Update GUI with Predictions
def add_prediction(self, file, prediction):
for i in self.tree.get_children():
if self.tree.item(i)['values'][1] == file:
self.tree.item(i, values=("☑️", file, str(prediction)))
break
def set_target(self, v):
self.progress["value"] = v
def finish(self):
messagebox.showinfo("Done", "Predictions completed!")
- Run the App
Finally, start the Tkinter main loop:
if __name__ == "__main__":
app = InsurePredictApp()
app.root.mainloop()
Your app is now ready! You can drag & drop CSV files, run batch predictions, and see results in real-time.
- Clone the Full Project
You can get the full code with all features here:
https://github.com/rogers-cyber/python-tiny-tools/tree/main/Insurance-cost-prediction-GUI
✅ Key Takeaways:
Tkinter + ttkbootstrap = modern GUI in Python
Threads keep the GUI responsive during long tasks
LinearRegression allows basic AI predictions
Drag & Drop and batch CSV support improve UX

Top comments (0)