DEV Community

Mate Technologies
Mate Technologies

Posted on

🏠 Build a Machine Learning–Powered House Rent Predictor (Python + Tkinter)

In this tutorial, we’ll build RentPredictor v1.0, a desktop application that estimates house rent using Machine Learning and a modern Python UI.

No advanced ML knowledge required — we’ll break everything down step by step 👇

📌 What We’ll Build

A desktop app that:

Takes house details (size, BHK, bathrooms, city type)

Predicts monthly rent using an ML model

Uses a modern dark UI

Runs predictions without freezing the app

🛠️ Tech Stack

Python

Tkinter + ttkbootstrap (modern UI)

NumPy

Joblib (load ML model)

Threading (smooth UI)

📂 Project Structure
House-rent-prediction-app/

├── rent_model.pkl
├── logo.ico
├── app.py
└── requirements.txt

🔗 GitHub Repository

Clone the project directly from GitHub:

https://github.com/rogers-cyber/python-tiny-tools/tree/main/House-rent-prediction-app

1️⃣ Import Required Libraries

We start by importing everything the app needs.

import os
import sys
import threading
import tkinter as tk
from tkinter import messagebox

import numpy as np
import joblib

import ttkbootstrap as tb
from ttkbootstrap.constants import *
Enter fullscreen mode Exit fullscreen mode

💡 Why these?

tkinter → GUI

ttkbootstrap → modern theme

joblib → load ML model

threading → keep UI responsive

2️⃣ Handling File Paths (Important for EXE Builds)

This helper ensures files work whether running as .py or .exe.

def resource_path(file_name):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, file_name)
Enter fullscreen mode Exit fullscreen mode

3️⃣ Prediction Worker (Background Thread)

We don’t want the UI to freeze while predicting rent.

class PredictionWorker:
    def __init__(self, model, features, callback):
        self.model = model
        self.features = features
        self.callback = callback
Enter fullscreen mode Exit fullscreen mode

Run prediction safely:

    def run(self):
        try:
            prediction = self.model.predict([self.features])[0]
            self.callback(round(prediction, 2))
        except Exception as e:
            self.callback(None, str(e))
Enter fullscreen mode Exit fullscreen mode

✔ Runs in background
✔ Handles errors cleanly

4️⃣ Main Application Class

This is the heart of the app.

class RentPredictorApp:
    APP_NAME = "RentPredictor"
    APP_VERSION = "1.0"
Enter fullscreen mode Exit fullscreen mode

5️⃣ Initialize the Window

def __init__(self):
    self.root = tb.Window(themename="darkly")
    self.root.title(f"{self.APP_NAME} v{self.APP_VERSION}")
    self.root.minsize(900, 520)

Set app icon (optional):
    try:
        self.root.iconbitmap(resource_path("logo.ico"))
    except:
        pass
Enter fullscreen mode Exit fullscreen mode

6️⃣ Load the ML Model (With Fallback)

def _load_model(self):
    try:
        return joblib.load(resource_path("rent_model.pkl"))
Enter fullscreen mode Exit fullscreen mode

Dummy model if ML file is missing:

    except:
        class DummyModel:
            def predict(self, X):
                size, bhk, bath, city = X[0]
                return [size * 25 + bhk * 1500 + bath * 1000 + city * 2000]
        return DummyModel()
Enter fullscreen mode Exit fullscreen mode

💡 This keeps the app working even without a trained model.

7️⃣ Build the User Interface
Main container

main = tb.Frame(self.root, padding=15)
main.pack(fill=BOTH, expand=True)
Enter fullscreen mode Exit fullscreen mode

App title

tb.Label(
    main,
    text="🏠 RentPredictor - Smart Rent Estimation",
    font=("Segoe UI", 22, "bold")
).pack(pady=(0, 5))
Enter fullscreen mode Exit fullscreen mode

8️⃣ Input Form (Property Details)

form = tb.Labelframe(main, text="Property Details", padding=15)
form.pack(fill=X, pady=(0, 20))
Enter fullscreen mode Exit fullscreen mode

Input variables

self.size_var = tk.DoubleVar()
self.bhk_var = tk.IntVar()
self.bath_var = tk.IntVar()
Enter fullscreen mode Exit fullscreen mode

9️⃣ Reusable Input Field Function

def _add_field(self, parent, label, var, row):
    tb.Label(parent, text=label).grid(row=row, column=0, sticky=W, pady=5)
    tb.Entry(parent, textvariable=var).grid(row=row, column=1, sticky=EW, pady=5)
Enter fullscreen mode Exit fullscreen mode

Used for:

House size

BHK

Bathrooms

🔟 City Selector (Dropdown)

self.city_combo = tb.Combobox(
    form,
    values=["Small City", "Metro City"],
    state="readonly"
)
self.city_combo.current(0)
Enter fullscreen mode Exit fullscreen mode

1️⃣1️⃣ Predict Button & About Button

self.predict_btn = tb.Button(
    actions,
    text="🔮 Predict Rent",
    bootstyle=SUCCESS,
    command=self.predict
)

tb.Button(
    actions,
    text="ℹ️ About",
    bootstyle=INFO,
    command=self.show_about
)
Enter fullscreen mode Exit fullscreen mode

1️⃣2️⃣ Prediction Logic

def predict(self):
    size = self.size_var.get()
    bhk = self.bhk_var.get()
    bath = self.bath_var.get()
    city = 1 if self.city_combo.get() == "Metro City" else 0
Enter fullscreen mode Exit fullscreen mode

Validate input:

if size <= 0 or bhk <= 0 or bath <= 0:
    raise ValueError
Enter fullscreen mode Exit fullscreen mode

1️⃣3️⃣ Run Prediction in Background

worker = PredictionWorker(
    self.model,
    [size, bhk, bath, city],
    self.show_result
)

threading.Thread(target=worker.run, daemon=True).start()
Enter fullscreen mode Exit fullscreen mode

✔ No freezing
✔ Smooth UX

1️⃣4️⃣ Display Result

def show_result(self, rent, error=None):
    if error:
        messagebox.showerror("Prediction Error", error)
    else:
        self.result_label.config(
            text=f"Estimated Monthly Rent: ₹ {rent:,}"
        )
Enter fullscreen mode Exit fullscreen mode

1️⃣5️⃣ About Dialog

def show_about(self):
    messagebox.showinfo(
        "About RentPredictor",
        "Machine Learning powered rent estimation\nBuilt with Python"
    )
Enter fullscreen mode Exit fullscreen mode

1️⃣6️⃣ Run the App

if __name__ == "__main__":
    app = RentPredictorApp()
    app.run()
Enter fullscreen mode Exit fullscreen mode

🎉 Final Result

You now have:

A desktop ML application

A modern UI

A scalable project structure

Beginner-friendly Python architecture

🚀 What to Improve Next?

Train a real ML model

Add more city categories

Export predictions to CSV

Convert to .exe using PyInstaller

🧠 Final Thoughts

This project is a great example of how Python + Machine Learning + UI can solve real-world problems.

If you found this helpful, give the repo a ⭐ and keep building!

Happy coding! 🐍✨

Top comments (0)