Mini-project Report File(CSE)
Mini-project Report File(CSE)
REPORT
On
“SCIENTIFIC CALCULATOR
APPLICATION”
Submitted in partial fulfillment towards the award of degree in
B.TECH in Computer Science and Engineering
SESSION 2023-24
ODD SEMESTER
SUBMITTED BY:
Alok Kumar
ROLL NO:2208020109004
CSE/3rd Year
III
INDEX
IV
ACKNOWLEDGEMENT
(Sign of Student)
Alok Kumar
ROLL
NO:2208020109004
CSE/2nd Year
V
DECLARATION
I ALOK KUMAR (ROLL NO.2208020109004) hereby declare that the report
of Mini-Project titled “Scientific Calculator ” is uniquely prepared by me and
does not form part of any other thesis or dissertation on the basis of which a
degree or award was conferred on an earlier occasion on this or any other
candidate.
I also confirm that the report is only prepared for my academic requirement,
not for any other purpose. It might not be used with the interest of the opposite
party of the any organization.
Alok Kumar
ROLL
NO:2208020109004
CSE/2nd Year
VI
ABSTRACT
A scientific calculator is a type of electronic calculator, usually but not always handheld,
designed to calculate problems in science, engineering, and mathematics. They have
completely replaced slide rules in traditional applications, and are widely used in both
education and professional. The python calculator was implemented using tkinter to make
the calculation of mathematical functions easier. The application consists of scientific and
standard functions. The standard is used to solve scientific notation type math functions like
sin, cos, tan, log etc.
VII
LIST OF TABLES
1.Button layout Table:
Describes the layout of buttons on the calculator, showing the
arrangement of digits, arithmetic operations, and scientific
functions.
Button Description
1-9 Digits 1-9
0 Digit 0
. Decimal Point
= Equals
+ Addition
- Subtraction
x Multiplication
/ Division
C Clear
AC All Clear
√ Square Root
^ Exponentiation
x! Factorial
toRad Convert to Radians
toDeg Convert to Degrees
sinθ Sine Function
cosθ Cosine Function
tanθ Tangent Function
2.Functionality Table:
Describes the functionality associated with each button press or
action.
Button Functionality
1-9 Append respective digit to the input
0 Append '0' to the current input
. Append '.' to the current input
= Evaluate the expression and display the result
+ Append '+' to the current input
- Append '-' to the current input
x Append '*' to the current input
/ Append '/' to the current input
C Clear the last character in the input
AC Clear all input
√ Calculate the square root of the current input
^ Calculate the power/exponentiation
x! Calculate the factorial
toRad Convert the value to radians
toDeg Convert the value to degrees
sinθ Calculate the sine of the value in degrees
VIII
Button Functionality
cosθ Calculate the cosine of the value in degrees
tanθ Calculate the tangent of the value in degrees
This is a general breakdown of the functionality and layout of the calculator. You
may customize it further based on your needs or add additional features.
LIST OF FIGURES
In the context of a Tkinter-based calculator code, figures usually refer to graphical elements such as
buttons, labels, and frames. Here's a list of figures, or graphical components, that are part of your
calculator GUI:
IX
1. Calculator Image:
3. Textfield:
- The entry widget used for input and display of calculations.
12. Frames:
- Frames used to organize and group different sections of the calculator, such as `buttonframe` for
standard buttons and `scframe` for scientific buttons.
X
These are the main graphical elements/components in your calculator GUI. If you have used any
external images or icons, you might want to include those in your list as well.
XI
Chapter:1 Introduction
Python offers multiple options for developing a GUI (Graphical User Interface).
Out of all the GUI methods, Tkinter is the most commonly used method. It is a
standard Python interface to the Tk GUI toolkit shipped with Python. Python
with Tkinter outputs the fastest and easiest way to create GUI applications.
Creating a GUI using Tkinter is an easy task.
To create a Tkinter:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets
1.1 Background:
The project aims to develop a user-friendly Scientific Calculator using the Tkinter library in Python.
Calculators are essential tools for performing various mathematical operations, and this project
enhances the basic calculator functionalities by incorporating advanced scientific features.
1.2 Motivation:
The motivation behind this project is to create a versatile calculator that caters to both basic and
scientific calculation needs. The user interface is designed to be intuitive, making it accessible to a
wide range of users.
scientific calculator implemented in Python using the Tkinter library for the graphical user
interface. The calculator offers both standard and scientific functionality, allowing users to perform a
variety of mathematical operations.
3.User-Friendly Interface:
Clear and organized layout with numeric buttons, operation buttons, and a text field to display
input and results.
Integration of an image at the top for aesthetic appeal.
4.Error Handling:
The calculator incorporates error handling to manage exceptions during expression evaluation,
providing users with informative error messages.
5.Switchable Modes:
1
Users can switch between a standard calculator mode and a scientific calculator mode, enhancing
flexibility.
Identified Issues and Proposed Improvements:
The code review revealed several areas for enhancement, including improvements in the user
interface, error handling, code organization, and adherence to best coding practices. The proposed
solutions aim to address these issues and elevate the overall quality of the calculator program.
Objectives:
Documentation:
Add comments to clarify complex sections of code.
Provide docstrings for functions to document their purpose and usage.
Through the proposed solutions and methodologies, the objective is to transform the existing
calculator into a more user-friendly, robust, and maintainable application. The ensuing sections of the
document will delve into each identified issue and outline the steps taken to implement the proposed
solutions.
2. Error Handling:
The code currently catches exceptions during evaluation and shows
an error message box. Consider providing more specific error
messages or handling different types of errors more gracefully.
3. Code Structure:
The code could be organized into functions and classes for better
readability and maintainability.
Consider separating the GUI setup, normal calculator logic, and
scientific calculator logic into different functions or classes.
4. Magic Numbers:
Replace magic numbers in the code with named constants or
variables for better code readability. For example, the window
dimensions (445x570, 445x705) could be defined as constants.
6. Variable Naming:
Choose more descriptive variable names to improve code
readability.
Avoid using single-letter variable names unless they are
conventional (e.g., e for an exception).
7. Redundant Code:
There are redundant print statements used for debugging. Remove
or comment out these statements in the final version of the code.
8. Separation of Concerns:
Consider separating the calculator logic from the GUI code. This will
make it easier to modify or extend the calculator in the future.
9. Code Optimization:
The use of eval for calculation might be risky. Consider using safer
alternatives to evaluate expressions.
3
10.File Paths:
The path to the image file is currently hard-coded. Make sure the
image file is included with the code or use a relative path.
11.Consistent Style:
Ensure consistent coding style throughout the program, including
indentation, spacing, and naming conventions.
12.Testing:
Test the calculator thoroughly with various inputs to identify and fix
any unexpected behavior.
4
Consider using a grid layout manager to organize buttons
systematically.
Add labels to indicate the current mode and improve the overall
aesthetics of the GUI.
2. Error Handling:
Provide more specific error messages for different types of
exceptions.
Enhance the error handling to give users a clear understanding of
what went wrong.
3. Code Structure:
Organize the code into functions or classes.
Use separate functions for GUI setup, normal calculator logic, and
scientific calculator logic.
4. Magic Numbers:
Define constants for magic numbers, such as window dimensions.
5. Comments and Documentation:
Add comments to explain complex sections of code.
Provide docstrings for functions to document their purpose and
usage.
6. Variable Naming:
Use descriptive variable names for better readability.
7. Redundant Code:
Remove or comment out redundant print statements used for
debugging.
8. Separation of Concerns:
Separate the calculator logic from the GUI code to improve
maintainability.
9. Code Optimization:
Avoid using eval for calculations. Instead, use safer alternatives,
such as parsing and evaluating expressions.
10.File Paths:
Use relative paths or include the image file with the code.
11.Consistent Style:
Ensure consistent coding style, including indentation and spacing.
12.Testing:
Thoroughly test the calculator with various inputs to identify and fix
any unexpected behavior.
By implementing these proposed solutions, you can enhance the code quality,
maintainability, and user experience of the scientific calculator.
5
1. Python Installation:
Ensure that Python is installed on your system. The code is written
in Python 3, and it's recommended to have Python 3.6 or later.
2. Tkinter Library:
Tkinter is the standard GUI (Graphical User Interface) library for
Python and is used in the code for creating the calculator
interface. Tkinter is included with most Python installations, so
you typically don't need to install it separately.
3. Image File:
The code includes an image file ("img2.png") for the calculator's
picture label. Make sure that the image file is present in the
specified path or update the code with the correct path to the
image file.
4. Operating System:
The code is platform-independent and should run on Windows,
macOS, and Linux systems.
5. Additional Notes:
If you encounter any issues related to missing modules, you can
install them using the following command:
Ensure that the code is saved with the ".py" extension, and run it
using a Python interpreter.
The code uses the “math” module for mathematical functions, and
this module is part of the standard library.
2.Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform
the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the
user.
Example: This would create
#!/usr/bin/python a following window: –
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a
GUI application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well
as a brief description in the following : −
Operator & Description
1 Button - The Button widget is used to display buttons in your application.
2 Canvas - The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.
8
4 Entry - The Entry widget is used to display a single-line text field for accepting values from
a user.
5 Frame - The Frame widget is used as a container widget to organize other widgets.
6 Label - The Label widget is used to provide a single-line caption for other widgets. It can
also contain images.
9 Menu - The Menu widget is used to provide various commands to a user. These commands
are contained inside Menubutton.
10 Message - The Message widget is used to display multiline text fields for accepting values from
a user.
11 Radiobutton - The Radiobutton widget is used to display a number of options as radio buttons.
The user can select only one option at a time.
13 Scrollbar - The Scrollbar widget is used to add scrolling capability to various widgets, such as
list boxes.
16 Spinbox - The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
17 PanedWindow - A PanedWindow is a container widget that may contain any number of panes,
arranged horizontally or vertically.
18 LabelFrame - A labelframe is a simple container widget. Its primary purpose is to act as a spacer
or container for complex window layouts.
#scientific calculator
from tkinter import*
from tkinter.messagebox import *
import math as m
#some useful variables
font=("Verdana",18,'bold ')
#important function
def clear():
ex=textfield.get()
9
ex=ex[0:len(ex)-1]
textfield.delete(0,END)
textfield.insert(0,ex)
def all_clear():
textfield.delete(0,END)
textfield.insert(0, '0')
def click_btn_function(event):
global p
print("Button Clicked")
b=event.widget
text=b['text']
print(text)
if text=="x":
textfield.insert(END,"*")
return
if text=="=":
try:
ex=textfield.get()
answer=eval(ex)
textfield.delete(0,END)
textfield.insert(0,answer)
except Exception as e:
print("Error..",e)
showerror("Error",e)
return
if textfield.get() == '0':
textfield.delete(0, END)
textfield.insert(END,text)
#windows
window=Tk()
window.title("🔢 My Calculator")
window.geometry("445x570")
#picture label
pic=PhotoImage(file="D:\Project\img2.png")
headinglabel=Label(window,image=pic)
headinglabel.pack(side=TOP,pady=15)
#heading label
heading=Label(window,text="My calculator",font=font,underline=0)
heading.pack(side=TOP)
#textfield
textfield=Entry(window,font=font,justify=RIGHT)
textfield.pack(side=TOP,pady=10,fill=X,padx=10)
textfield.insert(0, '0')
#buttons
buttonframe=Frame(window)
buttonframe.pack(side=TOP)
#adding buttons
10
temp=1
for i in range(0,3):
for j in range(0,3):
btn=
Button(buttonframe,text=str(temp),font=font,width=5,relief=RIDGE,
activebackground="orange",activeforeground="white")
btn.grid(row=i,column=j)
temp=temp+1
btn.bind("<Button-1>",click_btn_function)
zerobtn=
Button(buttonframe,text="0",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
zerobtn.grid(row=3,column=0)
dotbtn=
Button(buttonframe,text=".",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
dotbtn.grid(row=3,column=1)
equalbtn=
Button(buttonframe,text="=",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
equalbtn.grid(row=3,column=2)
plusbtn=
Button(buttonframe,text="+",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
plusbtn.grid(row=0,column=3)
minusbtn=
Button(buttonframe,text="-",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
minusbtn.grid(row=1,column=3)
multbtn=
Button(buttonframe,text="x",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
multbtn.grid(row=2,column=3)
divbtn=
Button(buttonframe,text="/",font=font,width=5,relief=RIDGE,active
background="orange",activeforeground="white")
divbtn.grid(row=3,column=3)
clearbtn=
Button(buttonframe,text="C",font=font,width=11,relief=RIDGE,activ
ebackground="orange",activeforeground="white",command=clear)
clearbtn.grid(row=4,column=0,columnspan=2)
allclearbtn=
Button(buttonframe,text="AC",font=font,width=11,relief=RIDGE,acti
vebackground="orange",activeforeground="white",command=all_clear)
allclearbtn.grid(row=4,column=2,columnspan=2)
11
#binding buttons
plusbtn.bind("<Button-1>",click_btn_function)
minusbtn.bind("<Button-1>",click_btn_function)
multbtn.bind("<Button-1>",click_btn_function)
divbtn.bind("<Button-1>",click_btn_function)
zerobtn.bind("<Button-1>",click_btn_function)
dotbtn.bind("<Button-1>",click_btn_function)
equalbtn.bind("<Button-1>",click_btn_function)
def enterClick(event):
print("hi")
e=Event()
e.widget=equalbtn
click_btn_function(e)
textfield.bind("<Return>",enterClick)
#################################################################
######
#functions...
scframe=Frame(window)
#Buttons....
sqrtbtn=Button(scframe,text="√",font=font,width=5,relief=RIDGE,ac
tivebackground="orange",activeforeground="white")
sqrtbtn.grid(row=0,column=0)
powbtn=Button(scframe,text="^",font=font,width=5,relief=RIDGE,act
ivebackground="orange",activeforeground="white")
powbtn.grid(row=0,column=1)
factbtn = Button(scframe, text='x!', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
factbtn.grid(row=0, column=2)
radbtn = Button(scframe, text='toRad', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
radbtn.grid(row=0, column=3)
degbtn = Button(scframe, text='toDeg', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
degbtn.grid(row=1, column=0)
sinbtn = Button(scframe, text='sinθ', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
sinbtn.grid(row=1, column=1)
cosbtn = Button(scframe, text='cosθ', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
cosbtn.grid(row=1, column=2)
12
tanbtn = Button(scframe, text='tanθ', font=font, width=5,
relief='ridge',
activebackground='orange',activeforeground='white')
tanbtn.grid(row=1, column=3)
normalcalc=TRUE
def calculate_sc(event):
print("btn..")
btn=event.widget
text=btn['text']
print(text)
ex=textfield.get()
answer=""
if text=='toDeg':
print("cal degree")
answer=str(m.degrees(float(ex)))
elif text=="toRad":
print('radian')
answer=str(m.radians(float(ex)))
elif text=="x!":
print("cal factoria")
answer=str(m.factorial(int(ex)))
elif text=="sinθ":
print("cal sin")
answer=str(m.sin(m.radians(int(ex))))
elif text=="cosθ":
print("cal cos")
answer=str(m.cos(m.radians(int(ex))))
elif text== "tanθ":
print("cal tag")
answer=str(m.tan(m.radians(int(ex))))
if text=="√":
print("SQRT")
answer=m.sqrt(int(ex))
elif text=="^":
print("pow")
base,pow=ex.split(",")
print(base)
print(pow)
answer=m.pow(int(base),int(pow))
textfield.delete(0,END)
textfield.insert(0,answer)
def sc_click():
global normalcalc
if normalcalc:
buttonframe.pack_forget()
13
#add sc frame
scframe.pack(side=TOP,pady=20)
buttonframe.pack(side=TOP)
window.geometry("445x705")
#sc
print("show scientific")
normalcalc=False
else:
print("show normal")
scframe.pack_forget()
window.geometry("445x570")
normalcalc=True
#binding sc buttons
sqrtbtn.bind("<Button-1>",calculate_sc)
powbtn.bind("<Button-1>",calculate_sc)
factbtn.bind("<Button-1>",calculate_sc)
radbtn.bind("<Button-1>",calculate_sc)
degbtn.bind("<Button-1>",calculate_sc)
cosbtn.bind("<Button-1>",calculate_sc)
sinbtn.bind("<Button-1>",calculate_sc)
tanbtn.bind("<Button-1>",calculate_sc)
fontMenu=("",15)
menubar=Menu(window)
mode=Menu(menubar,font=fontMenu,tearoff=0)
mode.add_checkbutton(label="Scientific
Calculator",command=sc_click)
menubar.add_cascade(label="mode",menu=mode)
window.config(menu=menubar)
window.mainloop()
RESULT
The provided code is a Python program that creates a graphical calculator using the Tkinter
library. The calculator has two modes: a basic calculator and a scientific calculator. Here's
a breakdown of the main components and functionalities:
1. Basic Calculator:
The basic calculator includes buttons for digits 0-9, arithmetic operations (+, -,
*, /), a decimal point (.), and an equals (=) button.
14
The click_btn_function function handles button clicks and performs the
corresponding actions. It updates the entry field with the pressed button's text.
The clear function removes the last character from the entry field.
The all_clear function clears the entire entry field.
2. Scientific Calculator:
The scientific calculator mode can be activated by checking the "Scientific
Calculator" option in the menu.
Additional scientific functions include square root (√), power (^), factorial
(x!), conversion between degrees and radians (toDeg, toRad), and
trigonometric functions (sinθ, cosθ, tanθ).
The calculate_sc function handles the scientific calculator button clicks and
performs the corresponding scientific calculations.
3. Graphical User Interface (GUI):
The Tkinter library is used for creating the graphical user interface.
The main window contains a title, a picture label, a heading label, and an
entry field for input and display.
Calculator buttons are organized in a grid layout using the Button widget and
are bound to the click_btn_function for basic calculator buttons and
calculate_sc for scientific calculator buttons.
There is a menu bar with an option to switch between basic and scientific
calculator modes.
4. Menu and Mode Switching:
The menu bar includes an option to toggle between basic and scientific
calculator modes.
Clicking on the "Scientific Calculator" option switches the calculator to the
scientific mode, revealing additional buttons.
5. Event Handling:
The code handles events such as button clicks and Enter key presses.
The enterClick function is triggered when the Enter key is pressed, and it
simulates a click on the equals (=) button.
6. Code Organization:
The code is organized into functions for better readability and maintainability.
Comments are added to explain the purpose and functionality of different
sections of the code.
7. User Interface Elements:
The calculator's appearance is enhanced with a picture label at the top,
providing a visual element to the GUI.
8. Error Handling:
Some basic error handling is implemented for the evaluation of expressions in
the basic calculator, and more advanced error handling could be added based
on specific use cases.
Output
15
After clicking Mode then
ScientificCalculator :-
16
6.Conclusion
The proposed system is error free. Trivial concepts of Python language are implemented into the
system. As, the usage of Python Tkinter as the GUI provided various controls, such as buttons, labels,
and text boxes to build a user friendly application. The rapid expansion and use of the internet,
confirms the splendid future and scope of the project.
17