Calculator GUI
Abstract
Create a fully functional calculator with a graphical user interface that supports basic arithmetic operations, decimal numbers, error handling, and clear functionality. This project demonstrates GUI design, event handling, and mathematical expression evaluation.
Prerequisites
- Python 3.6 or above
- Text Editor or IDE
- Basic understanding of Python syntax
- Knowledge of Tkinter for GUI development
- Familiarity with arithmetic operations
- Understanding of event-driven programming
Getting Started
Create a new project
- Create a new project folder and name it
calculatorGUI
calculatorGUI
. - Create a new file and name it
calculatorgui.py
calculatorgui.py
. - Open the project folder in your favorite text editor or IDE.
- Copy the code below and paste it into your
calculatorgui.py
calculatorgui.py
file.
Write the code
- Add the following code to your
calculatorgui.py
calculatorgui.py
file.
⚙️ Calculator GUI
# Calculator with GUI using Tkinter
from tkinter import *
solution = ""
def press(num):
global solution
solution = solution + str(num)
equation.set(solution)
def equalpress():
try:
global solution
total = str(eval(solution))
equation.set(total)
solution = ""
except:
equation.set(" error ")
solution = ""
def clear():
global solution
solution = ""
equation.set("")
if __name__ == "__main__":
gui = Tk()
gui.configure(background="light green")
gui.title("Calculator")
gui.geometry("270x150")
equation = StringVar()
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
equation.set('enter your expression')
button1 = Button(gui, text=' 1 ', fg='black', bg='gray',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='gray',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='gray',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='gray',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='gray',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='gray',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='gray',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='gray',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='gray',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='gray',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='gray',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='gray',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='gray',
command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='gray',
command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='gray',
command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='gray',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='gray',
command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
gui.mainloop()
# Calculator with GUI using Tkinter
from tkinter import *
solution = ""
def press(num):
global solution
solution = solution + str(num)
equation.set(solution)
def equalpress():
try:
global solution
total = str(eval(solution))
equation.set(total)
solution = ""
except:
equation.set(" error ")
solution = ""
def clear():
global solution
solution = ""
equation.set("")
if __name__ == "__main__":
gui = Tk()
gui.configure(background="light green")
gui.title("Calculator")
gui.geometry("270x150")
equation = StringVar()
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
equation.set('enter your expression')
button1 = Button(gui, text=' 1 ', fg='black', bg='gray',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='gray',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='gray',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='gray',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='gray',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='gray',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='gray',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='gray',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='gray',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='gray',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='gray',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='gray',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='gray',
command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='gray',
command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='gray',
command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='gray',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='gray',
command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
gui.mainloop()
- Save the file.
- Run the following command to run the application.
C:\Users\username\Documents\calculatorGUI> python calculatorgui.py
[Calculator GUI Opens]
- Click number buttons to input values
- Click operation buttons (+, -, *, /) for calculations
- Click "=" to get the result
- Click "Clear" to reset the calculator
Example: 5 + 3 = 8
C:\Users\username\Documents\calculatorGUI> python calculatorgui.py
[Calculator GUI Opens]
- Click number buttons to input values
- Click operation buttons (+, -, *, /) for calculations
- Click "=" to get the result
- Click "Clear" to reset the calculator
Example: 5 + 3 = 8
## Explanation
1. The `from tkinter import *` statement imports all Tkinter components for creating the GUI.
2. The `solution = ""` creates a global variable to store the current mathematical expression.
3. The `equation = StringVar()` creates a Tkinter string variable for the display.
4. The `def press(num):` function handles button presses and updates the expression.
5. The `def equalpress():` function evaluates the mathematical expression using eval().
6. The `def clear():` function resets the calculator by clearing the expression.
7. The `gui = Tk()` creates the main window for the calculator.
8. The `expression_field = Entry()` creates the display field for showing expressions and results.
9. The number buttons (0-9) are created with lambda functions to pass their values.
10. The operation buttons (+, -, *, /) handle arithmetic operations.
11. The grid layout system organizes buttons in a calculator-style arrangement.
12. Error handling displays "error" when invalid expressions are entered.
## Next Steps
Congratulations! You have successfully created a Calculator GUI in Python. Experiment with the code and see if you can modify the application. Here are a few suggestions:
- Add advanced mathematical functions (sin, cos, tan, log, sqrt)
- Implement memory functions (M+, M-, MR, MC)
- Add keyboard input support
- Create a history feature to track calculations
- Implement bracket support for complex expressions
- Add a scientific calculator mode
- Create different themes and color schemes
- Add sound effects for button presses
- Implement percentage calculations
## Conclusion
In this project, you learned how to create a Calculator GUI in Python using Tkinter. You also learned about GUI design, event handling, and mathematical expression evaluation. You can find the source code on [GitHub](https://github.com/Ravikisha/PythonCentralHub/blob/main/projects/beginners/calculatorgui.py)
## Code Explanation
### Global State Management
```python title="calculatorgui.py" showLineNumbers{1}
solution = ""
def press(num):
global solution
solution = solution + str(num)
equation.set(solution)
## Explanation
1. The `from tkinter import *` statement imports all Tkinter components for creating the GUI.
2. The `solution = ""` creates a global variable to store the current mathematical expression.
3. The `equation = StringVar()` creates a Tkinter string variable for the display.
4. The `def press(num):` function handles button presses and updates the expression.
5. The `def equalpress():` function evaluates the mathematical expression using eval().
6. The `def clear():` function resets the calculator by clearing the expression.
7. The `gui = Tk()` creates the main window for the calculator.
8. The `expression_field = Entry()` creates the display field for showing expressions and results.
9. The number buttons (0-9) are created with lambda functions to pass their values.
10. The operation buttons (+, -, *, /) handle arithmetic operations.
11. The grid layout system organizes buttons in a calculator-style arrangement.
12. Error handling displays "error" when invalid expressions are entered.
## Next Steps
Congratulations! You have successfully created a Calculator GUI in Python. Experiment with the code and see if you can modify the application. Here are a few suggestions:
- Add advanced mathematical functions (sin, cos, tan, log, sqrt)
- Implement memory functions (M+, M-, MR, MC)
- Add keyboard input support
- Create a history feature to track calculations
- Implement bracket support for complex expressions
- Add a scientific calculator mode
- Create different themes and color schemes
- Add sound effects for button presses
- Implement percentage calculations
## Conclusion
In this project, you learned how to create a Calculator GUI in Python using Tkinter. You also learned about GUI design, event handling, and mathematical expression evaluation. You can find the source code on [GitHub](https://github.com/Ravikisha/PythonCentralHub/blob/main/projects/beginners/calculatorgui.py)
## Code Explanation
### Global State Management
```python title="calculatorgui.py" showLineNumbers{1}
solution = ""
def press(num):
global solution
solution = solution + str(num)
equation.set(solution)
Maintains the current expression as a global string, updating the display whenever new input is added.
Expression Evaluation
def equalpress():
try:
global solution
total = str(eval(solution))
equation.set(total)
solution = ""
except:
equation.set(" error ")
solution = ""
def equalpress():
try:
global solution
total = str(eval(solution))
equation.set(total)
solution = ""
except:
equation.set(" error ")
solution = ""
Uses Python’s eval()
eval()
function to calculate mathematical expressions with proper error handling for invalid operations.
GUI Layout with Grid System
gui = Tk()
gui.configure(background="light green")
gui.title("Calculator")
gui.geometry("270x150")
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
gui = Tk()
gui.configure(background="light green")
gui.title("Calculator")
gui.geometry("270x150")
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
Creates a structured calculator layout using Tkinter’s grid system for organized button placement.
Number and Operation Buttons
button1 = Button(gui, text=' 1 ', fg='black', bg='gray',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
plus = Button(gui, text=' + ', fg='black', bg='gray',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
button1 = Button(gui, text=' 1 ', fg='black', bg='gray',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
plus = Button(gui, text=' + ', fg='black', bg='gray',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
Implements individual buttons for numbers (0-9) and operators (+, -, *, /) with lambda functions for command handling.
Clear Functionality
def clear():
global solution
solution = ""
equation.set("")
def clear():
global solution
solution = ""
equation.set("")
Provides a reset function to clear both the current expression and the display.
Features
- Standard Calculator Layout: Traditional button arrangement
- Basic Arithmetic Operations: Addition, subtraction, multiplication, division
- Decimal Number Support: Includes decimal point for floating-point calculations
- Real-Time Display: Shows current expression as it’s being built
- Error Handling: Displays “error” for invalid expressions
- Clear Function: Reset calculator to initial state
- Responsive Interface: Immediate visual feedback for button presses
Next Steps
Enhancements
- Add advanced mathematical functions (sin, cos, tan, log)
- Implement memory functions (M+, M-, MR, MC)
- Add keyboard input support
- Create calculation history feature
- Implement parentheses for complex expressions
- Add percentage calculations
- Include square root and power functions
- Implement better error messages
Learning Extensions
- Study mathematical expression parsing
- Explore custom number formatting
- Learn about calculator algorithms
- Practice with advanced GUI layouts
- Understand operator precedence rules
- Explore scientific calculator features
Educational Value
This project teaches:
- GUI Development: Creating interactive interfaces with buttons and displays
- Event Handling: Managing user interactions and button clicks
- State Management: Maintaining application state across user actions
- String Manipulation: Building and processing mathematical expressions
- Error Handling: Managing invalid input and calculation errors
- Grid Layout System: Organizing GUI components in structured layouts
- Lambda Functions: Using anonymous functions for button commands
- Expression Evaluation: Understanding how calculators process mathematical expressions
Perfect for understanding GUI application development, user interface design, and mathematical computation in programming.
Was this page helpful?
Let us know how we did