Create Calculator Program in Python, Download Source Code

Published on:

The Calculator is one application that we all use in our day-to-day lives. If you are trying to get your hands dirty with programming in python, Calculator is a project which is easy and valuable at the same time. Today, we will Create Calculator Program in Python using Tkinter with easy-to-understand steps.

What is Tkinter?

Python offers various utilities to design the GUI wiz Graphical User Interface, and one such utility is Tkinter which is most commonly used. It is one of the fastest and easiest ways to build a GUI application. Moreover, Tkinter is cross-platform. Hence the same code works on macOS, Windows, and Linux.

Create Calculator Program in Python

Step-by-step Approach:

  • Creating the main window
  • Creating a container containing all keys used in the calculator (Here List)
  • Creating a container for all our buttons created
  • Creating buttons and adding them to the button container
  • Defining the function to be called when a button is pressed
  • Running the main loop

Below is the implementation of the above approach:

Work on Python Calculator Project and get ready for a boost in your career

Step 1: Importing the necessary modules

To use the Tkinter, we need to import the Tkinter module.

Code:

# Import required modules
from tkinter import *
import tkinter.font as font

Step 2: Making a window for our Calculator

We will draft the window for our Calculator Program in Python, which will accommodate the buttons.

Code:

# Creating the main window
root = Tk()

# Assigning it the desired geometry
root.geometry("420x440")

# Assigning the name of our window
root.title("Calculator Project in Python - GetProjects.org")

# Running the main loop
root.mainloop()

Explanation:

The above code sets the title of the python calculator window as ‘Calculator Project in Python – GetProjects.org.’ You will get a GUI window when you run the above code.

Output:

Step 3: Designing the buttons and Mapping the buttons to their functionalities

Now let’s quickly design the buttons and Mapping the buttons to their functionalities for our Calculator and put them on our application window.

Code:

# Assigning it the capability to
# be resizable (It is default)
root.resizable(0, 0)

# Creating a StringVar to take
# the text entered in the Entry widget
inp = StringVar()
myFont = font.Font(size=15)

# Creating an Entry widget to get the
# mathematical expression
# And also to display the results
screen = Entry(root, text=inp, width=30,
			justify='right', font=(10), bd=4)

# We will use a grid like structure
screen.grid(row=0, columnspan=4, padx=15,
			pady=15, ipady=5)

# Key matrix contains all the required the keys
key_matrix = [["c", u"\u221A", "/", "<-"],
			["7", "8", "9", "*"],
			["4", "5", "6", "-"],
			["1", "2", "3", "+"],
			["!", 0, ".", "="]]

# Creating a dictionary for the buttons
btn_dict = {}

# Variable to store our results
ans_to_print = 0

# Defining the function for calculation
def Calculate(event):

	# getting the name of the button clicked
	button = event.widget.cget("text")

	# Referring the global values
	global key_matrix, inp, ans_to_print

	try:
		# Event containing a sqrt operation
		if button == u"\u221A":
			ans = float(inp.get())**(0.5)
			ans_to_print = str(ans)
			inp.set(str(ans))

		elif button == "c": # Clear Button
			inp.set("")

		elif button == "!": # Factorial
			def fact(n): return 1 if n == 0 else n*fact(n-1)
			inp.set(str(fact(int(inp.get()))))

		elif button == "<-": # Backspace
			inp.set(inp.get()[:len(inp.get())-1])

		elif button == "=": # Showing The Results
			# Calculating the mathematical exp. using eval
			ans_to_print = str(eval(inp.get()))
			inp.set(ans_to_print)

		# You may add many more operations

		else:
			# Displaying the digit pressed on screen
			inp.set(inp.get()+str(button))

	except:
		# In case invalid syntax given in expression
		inp.set("Wrong Operation")

		

# Creating the buttons using for loop

# Number of rows containing buttons
for i in range(len(key_matrix)):
	# Number of columns
	for j in range(len(key_matrix[i])):

		# Creating and Adding the buttons to dictionary
		btn_dict["btn_"+str(key_matrix[i][j])] = Button(
		root, bd=1, text=str(key_matrix[i][j]), font=myFont)
		
		# Positioning buttons
		btn_dict["btn_"+str(key_matrix[i][j])].grid(
		row=i+1, column=j, padx=5, pady=5, ipadx=5, ipady=5)
		
		# Assigning an action to the buttons
		btn_dict["btn_"+str(key_matrix[i][j])].bind('<Button-1>', Calculate)
Download the source code of the Calculator program in Python: Python Calculator Project.

Output of Calculator Program in Python

When you execute this calculator program in python, you will get the following screens:

Output Calculator Program in Python

Summary of Output of Calculator Program in Python

Hooray! We have successfully designed a calculator program in python with Tkinter. This means that you have a better understanding of how Tkinter is used to build GUI applications. Apart from this, you can now take a step forward to extend the project by making a history tab that keeps track of the previous calculations or adding a background image to the Calculator.

Some Recommended Projects
1. Create a Classic Tic-Tac-Toe Game in Python
2. Create a Notepad using Python
3. Create Fruit Ninja Game in Python

Keywords

  • Build a Python Calculator
Related Articles

Related

Leave a Reply

Please enter your comment!
Please enter your name here