Monday, 8 September 2025

Modern Calculator using Tkinter in Python

 



Code:

import tkinter as tk

class ModernCalculator:

    def _init_(self, root):

        self.root = root

        self.root.title("Modern Calculator")

        self.root.geometry("350x550")

        self.root.resizable(False, False)

        self.root.config(bg="#2E2E2E")  # Dark background

self.expression = ""

 # Heading bar

        heading_frame = tk.Frame(root, bg="#1C1C1E", height=60)

        heading_frame.pack(fill="x")

  heading = tk.Label(

            heading_frame, text="🧮 Modern Calculator",

            font=("Arial", 20, "bold"),

            bg="#1C1C1E", fg="#34C759"

        )

        heading.pack(pady=10)

 # Entry display

        self.display_var = tk.StringVar()

        self.display = tk.Entry(

            root, textvariable=self.display_var,

            font=("Arial", 24), bg="#3C3C3C", fg="white",

            bd=0, justify="right", insertbackground="white"

        )

        self.display.pack(fill="both", ipadx=8, ipady=20, padx=10, pady=10)

 # Buttons layout

        btns_frame = tk.Frame(root, bg="#2E2E2E")

        btns_frame.pack(expand=True, fill="both")

        buttons = [

            ("C", "#FF5C5C"), ("(", "#4D4D4D"), (")", "#4D4D4D"), ("/", "#FF9500"),

            ("7", "#737373"), ("8", "#737373"), ("9", "#737373"), ("*", "#FF9500"),

            ("4", "#737373"), ("5", "#737373"), ("6", "#737373"), ("-", "#FF9500"),

            ("1", "#737373"), ("2", "#737373"), ("3", "#737373"), ("+", "#FF9500"),

            ("0", "#737373"), (".", "#737373"), ("←", "#4D4D4D"), ("=", "#34C759"),

        ]

  # Place buttons in grid

        for i, (text, color) in enumerate(buttons):

            btn = tk.Button(

                btns_frame, text=text, font=("Arial", 18, "bold"),

                bg=color, fg="white", bd=0, relief="flat",

                activebackground="#666", activeforeground="white",

                command=lambda t=text: self.on_button_click(t)

            )

            btn.grid(row=i//4, column=i%4, sticky="nsew", padx=5, pady=5, ipadx=5, ipady=15)

 # Grid responsiveness

        for i in range(5):

            btns_frame.grid_rowconfigure(i, weight=1)

        for j in range(4):

            btns_frame.grid_columnconfigure(j, weight=1)

def on_button_click(self, char):

        if char == "C":

            self.expression = ""

        elif char == "←":

            self.expression = self.expression[:-1]

        elif char == "=":

            try:

                self.expression = str(eval(self.expression))

            except:

                self.expression = "Error"

        else:

            self.expression += str(char)

            self.display_var.set(self.expression)

if _name_ == "_main_":

    root = tk.Tk()

    ModernCalculator(root)

    root.mainloop()

Output:




Code Explanation:

1. Importing Tkinter
import tkinter as tk

Imports the tkinter library, which is used for creating GUI applications in Python.

We alias it as tk for shorter usage.

2. Calculator Class Setup
class ModernCalculator:
    def __init__(self, root):

Defines a class ModernCalculator which will create and manage the entire calculator UI.

__init__ is the constructor, which takes root (main Tkinter window) as an argument.

3. Window (Root) Configuration
self.root = root
self.root.title("Modern Calculator")
self.root.geometry("350x550")
self.root.resizable(False, False)
self.root.config(bg="#2E2E2E")  # Dark background

title("Modern Calculator"): sets the window title.

geometry("350x550"): sets the window size (width=350px, height=550px).

resizable(False, False): prevents resizing the window.

config(bg="#2E2E2E"): sets a dark background color.

4. Expression String
self.expression = ""

Stores the current mathematical expression typed by the user.

5. Heading Bar (Title Strip)
heading_frame = tk.Frame(root, bg="#1C1C1E", height=60)
heading_frame.pack(fill="x")

Creates a Frame (container) with a dark color.

pack(fill="x"): makes it stretch across the full window width (like a title strip).

heading = tk.Label(
    heading_frame, text="🧮 Modern Calculator",
    font=("Arial", 20, "bold"),
    bg="#1C1C1E", fg="#34C759"
)
heading.pack(pady=10)

Adds a label inside the heading bar.
Emoji 🧮 + "Modern Calculator" text.

Font size 20, bold, green color.

pady=10: vertical padding.

6. Display (Entry Widget)
self.display_var = tk.StringVar()

A special Tkinter variable that updates automatically when changed.

self.display = tk.Entry(
    root, textvariable=self.display_var,
    font=("Arial", 24), bg="#3C3C3C", fg="white",
    bd=0, justify="right", insertbackground="white"
)

Creates an input box (calculator screen).

textvariable=self.display_var: links the input to our variable.

Large font, dark gray background, white text.

justify="right": aligns text to the right.

insertbackground="white": makes the cursor white.

self.display.pack(fill="both", ipadx=8, ipady=20, padx=10, pady=10)

Adds padding around the display box.

Expands it horizontally.

7. Buttons Layout (Frame for Buttons)
btns_frame = tk.Frame(root, bg="#2E2E2E")
btns_frame.pack(expand=True, fill="both")

A frame to hold all calculator buttons.

Expands to fill available space.

bbuttons = [
    ("C", "#FF5C5C"), ("(", "#4D4D4D"), (")", "#4D4D4D"), ("/", "#FF9500"),
    ("7", "#737373"), ("8", "#737373"), ("9", "#737373"), ("*", "#FF9500"),
    ("4", "#737373"), ("5", "#737373"), ("6", "#737373"), ("-", "#FF9500"),
    ("1", "#737373"), ("2", "#737373"), ("3", "#737373"), ("+", "#FF9500"),
    ("0", "#737373"), (".", "#737373"), ("←", "#4D4D4D"), ("=", "#34C759"),
]


List of buttons with labels and background colors.

Example: "C" is red, numbers are gray, = is green.

9. Creating Buttons in a Grid
for i, (text, color) in enumerate(buttons):
    btn = tk.Button(
        btns_frame, text=text, font=("Arial", 18, "bold"),
        bg=color, fg="white", bd=0, relief="flat",
        activebackground="#666", activeforeground="white",
        command=lambda t=text: self.on_button_click(t)
    )
    btn.grid(row=i//4, column=i%4, sticky="nsew", padx=5, pady=5, ipadx=5, ipady=15)

Loops through each button and creates a Button widget.

row=i//4, column=i%4: places buttons in a 4-column grid.

command=lambda t=text: self.on_button_click(t): when clicked, calls on_button_click with the button’s text.

10. Grid Responsiveness
for i in range(5):
    btns_frame.grid_rowconfigure(i, weight=1)
for j in range(4):
    btns_frame.grid_columnconfigure(j, weight=1)

Makes the grid flexible: rows and columns expand evenly.

11. Button Click Handling
def on_button_click(self, char):
    if char == "C":
        self.expression = ""
    elif char == "←":
        self.expression = self.expression[:-1]
    elif char == "=":
        try:
            self.expression = str(eval(self.expression))
        except:
            self.expression = "Error"
    else:
        self.expression += str(char)

    self.display_var.set(self.expression)

Handles logic when buttons are clicked:

"C" → clears everything.

"←" → deletes last character (backspace).

"=" → evaluates the expression safely with eval().

Otherwise → appends character to the expression.

Finally updates the display with self.display_var.set(...).

12. Run the Application
if __name__ == "__main__":
    root = tk.Tk()
    ModernCalculator(root)
    root.mainloop()

Creates the Tkinter root window.

Instantiates the ModernCalculator class.

Starts the GUI event loop with mainloop().

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)