Home » Create a simple calculator using tkinter in Python

Create a simple calculator using tkinter in Python

by pqzrmred71

Here’s how to create a simple calculator using tkinter in Python.

This calculator will support basic operations: addition, subtraction, multiplication, and division.

The tkinter library will provide buttons for each digit (0-9), arithmetic operators (+, -, *, /), and additional buttons for clear (C) and equal (=).

Code

import tkinter as tk

# Set up the main application window
root = tk.Tk()
root.title("Calculator")
root.geometry("400x600")

# Create a StringVar to hold the calculator's display value
display_text = tk.StringVar()

# Function to update the display with button clicks
def click(button_value):
    current_text = display_text.get()
    display_text.set(current_text + str(button_value))

# Function to evaluate the expression in the display
def calculate():
    try:
        result = eval(display_text.get())  # Evaluate the expression in the display
        display_text.set(result)  # Update display with the result
    except Exception:
        display_text.set("Error")  # Show error if calculation fails

# Function to clear the display
def clear():
    display_text.set("")

# Entry widget for displaying the input and result
display_entry = tk.Entry(root, textvariable=display_text, font=("Helvetica", 28), justify="right", bd=10, insertwidth=2)
display_entry.grid(row=0, column=0, columnspan=4, pady=20)

# Create buttons for numbers, operators, and functions
buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    'C', '0', '=', '+'
]

# Place buttons on the grid
row_val = 1
col_val = 0
for button in buttons:
    if button == '=':
        tk.Button(root, text=button, width=10, height=3, command=calculate).grid(row=row_val, column=col_val, columnspan=2)
        col_val += 2
    elif button == 'C':
        tk.Button(root, text=button, width=10, height=3, command=clear).grid(row=row_val, column=col_val)
        col_val += 1
    else:
        tk.Button(root, text=button, width=10, height=3, command=lambda b=button: click(b)).grid(row=row_val, column=col_val)
        col_val += 1
    if col_val > 3:
        col_val = 0
        row_val += 1

# Run the main loop
root.mainloop()

Explanation

  1. Import the tkinter Module:
    • tkinter is the standard Python library for creating GUI applications. We import it as tk for easier access.
  2. Set Up the Main Application Window:
    • root = tk.Tk() initializes the main window.
    • root.title(“Calculator”) sets the window title to “Calculator.”
    • root.geometry(“400×600”) sets the window dimensions to 400×600 pixels.
  3. Create a StringVar for the Display Text:
    • display_text = tk.StringVar() creates a StringVar that will hold and update the text shown in the calculator display.
  4. Function Definitions:
    • click(button_value):
      • This function is called whenever a number or operator button is pressed.
      • It appends the button_value to the current text on the display by updating display_text.
    • calculate():
      • This function evaluates the expression in the display when the = button is pressed.
      • eval(display_text.get()) evaluates the mathematical expression as a Python expression.
      • If the expression is valid, display_text.set(result) updates the display with the result.
      • If an error occurs (e.g., division by zero), an exception is caught, and “Error” is shown.
    • clear():
      • This function clears the display when the C button is pressed.
      • display_text.set(“”) resets the display text to an empty string.
  5. Entry Widget for Displaying Input and Results:
    • display_entry = tk.Entry(…) creates an Entry widget to show the expression and result.
    • textvariable=display_text links the StringVar (display_text) to the Entry, so it updates whenever display_text changes.
    • font=(“Helvetica”, 28) sets the font size for better visibility.
    • justify=”right” aligns the text to the right for a calculator-like appearance.
    • bd=10, insertwidth=2 adds padding and a thicker border around the display.
    • .grid(row=0, column=0, columnspan=4, pady=20) places the display in the first row, spanning all four columns.
  6. Create Buttons for Digits, Operators, and Functions:
    • buttons is a list of button labels, including digits (0-9), operators (+, -, *, /), clear (C), and equals (=).
    • The loop iterates over each item in buttons to create a Button widget:
      • tk.Button(…, command=lambda b=button: click(b)):
        • For digits and operators, the command is set to a lambda function, which calls click(b), passing the button label as an argument.
      • Special Buttons:
        • If the button is =, it calls calculate() to evaluate the expression.
        • If the button is C, it calls clear() to reset the display.
    • Grid Layout:
      • .grid(row=row_val, column=col_val, …) places each button on the grid layout.
      • columnspan=2 for = ensures it spans two columns for a wider look.
      • row_val and col_val track the grid position and reset to the next row after four columns.
  7. Run the Main Loop:
    • root.mainloop() starts the tkinter event loop, keeping the window open and responsive to user input.

How the Calculator Works

  1. User Input:
    • The user clicks on the buttons to input numbers and operations.
    • Each button click updates the display with the entered number or operation.
  2. Calculating the Result:
    • When the = button is clicked, calculate() evaluates the entire expression on the display.
    • If the expression is valid, the result is displayed; otherwise, “Error” is shown.
  3. Clearing the Display:
    • When the C button is clicked, clear() resets the display, allowing the user to start a new calculation.

Summary

  • This simple calculator allows users to perform basic arithmetic operations using a GUI.
  • tkinter widgets (Button, Entry) create an interactive interface.
  • Functions (click, calculate, and clear) handle the core functionality of inputting numbers, evaluating expressions, and clearing the display.
  • This basic calculator is an example of how to use tkinter for creating interactive applications with event handling in Python.

This code can be expanded to add more calculator features such as scientific command like sin, cos and tan. There is also a lot of scope to improve the interface, can you see what improvements you can make

You may also like