How to display numbers in calculator, using TKinter in Python?


Tkinter, derived from "Tk interface," is the default GUI library bundled with Python. It provides a wide variety of widgets, including buttons, labels, entry fields, and more, making it a versatile choice for GUI development. Tkinter's cross-platform nature ensures that applications built with it can run on various operating systems without modification.

In the context of building a calculator, Tkinter offers the essential building blocks for creating a user interface with buttons and a display area. In this article, we'll harness the power of Tkinter to design a calculator that not only performs calculations but also does so with an interface that is intuitive and user-friendly.

Designing the Calculator Interface

Before delving into the coding part, it's important to outline the design of the calculator interface. Our goal is to create a basic calculator with a display screen and buttons for digits (0-9) and common arithmetic operations (+, -, *, and /). Additionally, we'll include a decimal point and an equals (=) button for performing calculations.

Here's a brief overview of the calculator's interface −

  • Display Screen − A prominent display area at the top of the calculator where users can see the numbers they input and the results of their calculations.

  • Buttons for Digits − Buttons for the digits 0 through 9, allowing users to input numbers.

  • Arithmetic Operation Buttons − Buttons for addition (+), subtraction (-), multiplication (*), and division (/), enabling users to perform basic calculations.

  • Decimal Point Button − A button to input decimal points in numbers.

  • Equals (=) Button − A button to trigger the calculation and display the result.

With the design in mind, let's proceed to the implementation using Python and Tkinter.

Implementing the Calculator in Python with Tkinter

To create our simple calculator, we'll follow a step-by-step process using Python and Tkinter. Below are the key steps and the corresponding Python code to build the calculator.

Step 1: Import the Required Modules

# import the tkinter module for GUI
import tkinter as tk

Step 2: Create the Main Window

# Create a Tkinter window
root = tk.Tk()
root.geometry("720x250")
# Set the window title
root.title("Displaying Numbers in Calculator")

Step 3: Design the Display Screen

# Create a variable to store the display text
display = tk.StringVar()
display.set("0")

# Create the calculator display screen
display_label = tk.Label(root, textvariable=display, font=("Arial", 24), anchor="e", background="white")
display_label.grid(row=0, column=0, columnspan=4)

Step 4: Create Buttons for Digits and Operations

# Create buttons for digits and operations
buttons = [
   "7", "8", "9", "/",
   "4", "5", "6", "*",
   "1", "2", "3", "-",
   "0", ".", "=", "+"
]

row_val = 1
col_val = 0

for button in buttons:
   tk.Button(root, text=button, padx=20, pady=20, font=("Arial", 18), command=lambda b=button: update_display(b) if b != "=" else calculate()).grid(row=row_val, column=col_val)
   col_val += 1
   if col_val > 3:
      col_val = 0
      row_val += 1

Step 5: Implement Functions for Updating Display and Calculating

# Function to update the calculator display
def update_display(value):
   current_text = display.get()
   if current_text == "0" or current_text == "Error":
      display.set(value)
   else:
      display.set(current_text + value)

# Function to perform calculations
def calculate():
   try:
      result = eval(display.get())
      display.set(result)
   except:
      display.set("Error")

Step 6: Start the Tkinter Main Loop

# Start the Tkinter main loop
root.mainloop()

Let's explore the complete implementation code and output of this simple calculator application.

Example

# import the tkinter module for GUI
import tkinter as tk
# Create a Tkinter window
root = tk.Tk()
root.geometry("720x400")
# Set the window title
root.title("Displaying Numbers in Calculator")
# Create a variable to store the display text
display = tk.StringVar()
display.set("0")

# Create the calculator display screen
display_label = tk.Label(root, textvariable=display, font=("Arial", 24), anchor="e", background="white")
display_label.grid(row=0, column=0, columnspan=4)
# Create buttons for digits and operations
buttons = [
   "7", "8", "9", "/",
   "4", "5", "6", "*",
   "1", "2", "3", "-",
   "0", ".", "=", "+"
]

row_val = 1
col_val = 0

for button in buttons:
   tk.Button(root, text=button, padx=20, pady=20, font=("Arial", 18), command=lambda b=button: update_display(b) if b != "=" else calculate()).grid(row=row_val, column=col_val)
   col_val += 1
   if col_val > 3:
      col_val = 0
      row_val += 1
# Function to update the calculator display
def update_display(value):
   current_text = display.get()
   if current_text == "0" or current_text == "Error":
      display.set(value)
   else:
      display.set(current_text + value)

# Function to perform calculations
def calculate():
   try:
      result = eval(display.get())
      display.set(result)
   except:
      display.set("Error")
# Start the Tkinter main loop
root.mainloop()

Output

Conclusion

In this article, we've explored the process of creating a simple calculator using Python and Tkinter, and the focus has not just been on the functionality but also on crafting an interface that enhances the user experience.

While this example represents a basic calculator, the principles and techniques demonstrated can be extended to create more complex calculators with additional features. Tkinter's simplicity and flexibility make it a valuable choice for developing graphical user interfaces, and Python's ease of use ensures that you can quickly bring your GUI application ideas to life.

Updated on: 05-Dec-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements