Scientific calculator using Python

Scientific calculator

Introduction:

In this project, we build up the scientific calculator using the tkinter library of Python. It is the standard GUI library for Python. With its help, we prepared the GUI for the project, and to add the functionalities of the scientific calculator, we used a math module. So, scroll down and get to know the steps!

Explanation:

The first step is importing all the necessary libraries using the “import” keyword. For the latest version, the tkinter module comes under the future module. So first, we have to install the future module with the help of the command “pip install <module-name>”. The future module is a built-in module in Python that inherits new features which is available in the latest Python versions. With “future. moves” we will import the tkinter module.

In the next step, to create an object of the tkinter frame will use “.Tk()”.With this, we will also set the title and geometry of our tkinter application. To set the background color for the project we will use “.config(bg=<color name>)”. And so, with that, we have set black as the background color for this project.

We will also add an image by the corner to give it a creative aspect. With the help of “.PhotoImage(file=<filename>)”, we will load the picture, by using the “.Label()” we will make the label widget for this, and “.grid(row=,column= )” will help to get it placed well on the window.

While working on this project, we need to fulfill three aspects.

  • Space for the calculation
  • Buttons for the calculation
  • Adding the functionalities

Talking about the first aspect, we will create an entry widget by “.Entry()”. Under this, we have provided the parameter such as

root – window object

font – The font style in which we want the information to get entered

bg – Stating the background color for the space

fg – Stating the color of the text appeared

bd – Border of the entry widget

width – width of the entry widget

Finally, with the help of “.grid()” we will set the position for the entry widget.

Source Code:

				
					# Importing the library
from future.moves import tkinter
import math


# To provide functionalities
def click(val):
    e = entry.get()  # getting the value
    ans = " "

    try:
        # To clear the last inserted text
        if val == "C":
            e = e[0:len(e) - 1]  # deleting the last entered value
            entry.delete(0, "end")
            entry.insert(0, e)
            return

        # To delete everything
        elif val == "CE":
            entry.delete(0, "end")

        # Square root
        elif val == "√":
            ans = math.sqrt(eval(e))

        # pi value
        elif val == "π":
            ans = math.pi

        # cos value
        elif val == "cosθ":
            ans = math.cos(math.radians(eval(e)))

        # sin value
        elif val == "sinθ":
            ans = math.sin(math.radians(eval(e)))

        # tan Value
        elif val == "tanθ":
            ans = math.tan(math.radians(eval(e)))

        # 2π value
        elif val == "2π":
            ans = 2 * math.pi

        # cosh value
        elif val == "cosh":
            ans = math.cosh(eval(e))

        # sinh value
        elif val == "sinh":
            ans = math.sinh(eval(e))

        # tanh value
        elif val == "tanh":
            ans = math.tanh(eval(e))

        # cube root value
        elif val == chr(8731):
            ans = eval(e) ** (1 / 3)

        # x to the power y
        elif val == "x\u02b8":
            entry.insert("end", "**")
            return

        # cube value
        elif val == "x\u00B3":
            ans = eval(e) ** 3

        # square value
        elif val == "x\u00B2":
            ans = eval(e) ** 2

        # ln value
        elif val == "ln":
            ans = math.log2(eval(e))

        # deg value
        elif val == "deg":
            ans = math.degrees(eval(e))

        # radian value
        elif val == "rad":
            ans = math.radians(eval(e))

        # e value
        elif val == "e":
            ans = math.e

        # log10 value
        elif val == "log10":
            ans = math.log10(eval(e))

        # factorial value
        elif val == "x!":
            ans = math.factorial(eval(e))

        # division operator
        elif val == chr(247):
            entry.insert("end", "/")
            return

        elif val == "=":
            ans = eval(e)

        else:
            entry.insert("end", val)
            return

        entry.delete(0, "end")
        entry.insert(0, ans)

    except SyntaxError:
        pass


# Created the object
root = tkinter.Tk()

# Setting the title and geometry
root.title("Scientific Calculator")
root.geometry("680x486+100+100")

# Setting the background color
root.config(bg="black")


# Entry field
entry = tkinter.Entry(root, font=("arial", 20, "bold"), bg="black", fg="white", bd=10, width=30)
entry.grid(row=0, column=0, columnspan=8)

# buttons list
button_list = ["C", "CE", "√", "+", "π", "cosθ", "tanθ", "sinθ", "1", "2", "3", "-", "2π", "cosh", "tanh", "sinh",
               "4", "5", "6", "*", chr(8731), "x\u02b8", "x\u00B3", "x\u00B2", "7", "8", "9", chr(247), "ln", "deg",
               "rad", "e", "0", ".", "%", "=", "log10", "(", ")", "x!"]
r = 1
c = 0
# Loop to get the buttons on window
for i in button_list:
    # Buttons
    button = tkinter.Button(root, width=5, height=2, bd=2, text=i, bg="black", fg="white",
                            font=("arial", 18, "bold"), command=lambda button=i: click(button))
    button.grid(row=r, column=c, pady=1)
    c += 1
    if c > 7:
        r += 1
        c = 0

# Makes window on loop
root.mainloop()
				
			

Getting into the next aspect, first of all, we have to create a list containing all the buttons that need to appear on the calculator. In this list, we will represent some characters by encoding them. Since the “.grid()” function works with row and column parameters. Therefore, we will take two variables for the same and then we run a “for” loop for creating the buttons by “.Buttons()”. The parameters under this widget are the same as before. But, in addition to this, it has a “command” parameter which will call the “click()” function. It is a UDF that consists of the block of code which will add the actual functionalities of the calculator. With that, we will set the positions for the buttons. To get the buttons systematically , according to the size of the window, we will use a condition. The condition says that if the column exceeds 7 then the row must get changed to place another button. That’s how we will be able to see all the buttons on the window.

The last thing is to add the functionalities, we will make a UDF named “click()”. Under this, with the help of an “if-else” ladder, we will check for the buttons that get pressed. First, we will get the information stored in the variable about the type of button pressed. To handle any of the syntax errors while calculating we will run a try and except block.

  • The first button stated “C” which is for clearing the last digit. To get this task done, we will first delete the last entered value by slicing. The next step is common to all operations, for displaying the result, we first have to delete the whole thing and then insert that particular result and this will be possible by “.delete()” & “.insert()”. The result will get stored in the variable.
  • Next button “CE”, to clear everything. It is being done by “.delete(0,” end”)”. The parameters passed state that the particular must get deleted from starting to end
  • The “square root” functionality is being added by using a function from the math module i.e. “.sqrt()”. The values passed under this function as parameters are under the “eval()” function which will allow the evaluation of arbitrary Python expressions from a string-based or compiled-code-based input.
  • Same as for all the other buttons such as, we will use the functions from the math module.

pi: math.pi

sinh: math.sinh()

cosh: math.cosh()

tanh: math.tanh()

cosθ: math.cos()

sinθ: math.sin()

tanθ: math.tan()

ln: math.log2()

deg: math.degrees()

rad: math.radians()

e: math.e

log10: math.log10()

x!: math.factorial()

Output:

scientific calculator output

For the numbers to be shown while getting the number buttons pressed we will give the command to insert the value in the “else” condition. In the end, we will run a tkinter event loop by “.mainloop()” , to make our project execute successfully!

Find More Projects

library management system using python with source code using Python GUI Tkinter (Graphical User Interface) How to Run the code: Introduction:  Imagine …

Space Shooter Game Using Python with source code Overview: A space shooter game typically involves controlling a spaceship to navigate through space …

Hotel Management System Using Python with source code Introduction: Welcome to our blog post introducing a helpful tool for hotels: the Tkinter-based …

Student Management System Using Python Introduction: The Student Management System is a comprehensive software solution designed to streamline the process of managing …

Billing Management System using Python introduction: The Billing software using python is a simple yet effective Python application designed to facilitate the …

Medical Management System using Python with Complete Source code [By using Flask Framework] Introduction Hospital Management System The Hospital Management System is …

More Python Projects
Get Huge Discounts

All Coding Handwritten Notes

Browse Handwritten Notes