How to build a simple calculator in Python
Learn how to build a simple calculator in Python using Tkinter. Follow this step-by-step tutorial and create a desktop application with buttons and basic arithmetic operations.
Tkinter is one of the easiest ways to get started with graphical user interface (GUI) development in Python. It comes included with most standard Python installations and provides the basic tools needed to build desktop applications.
In this tutorial, we will create a simple calculator using Python and Tkinter. The application will have a display, number buttons, basic arithmetic operators, and a button to calculate the result.
By the end of this tutorial, you will have a working calculator that can perform basic mathematical operations.
Watch the Tutorial
Follow the video below to see how the calculator is built step by step.
Prerequisites
Before getting started, make sure you have:
- Python installed on your computer.
- Basic knowledge of Python syntax and functions.
- A code editor, such as Visual Studio Code.
You do not need to install Tkinter separately if it is already included in your Python installation.
Step 1: Import the Required Libraries
First, we need to import Tkinter, which provides the components used to build our graphical interface.
from tkinter import *
from tkinter import ttkThe tkinter module provides widgets such as buttons, labels, frames, and windows. We also import ttk, which provides additional themed widgets.
Step 2: Define the Colors
Before creating the interface, let's define the colors that will be used throughout the application.
co1 = "#feffff" # White
co2 = "#6f9fbd" # Blue
co3 = "#38576b" # Display background
background = "#3b3b3b"
co10 = "#ECEFF1"
color1 = '#FFAB40'
color2 = '#ff333a'
color3 = '#6bd66f'
color4 = "#ab8918"Using variables for colors makes it easier to maintain the appearance of the application. If you decide to change the design later, you can update the colors in one place instead of modifying every widget individually.
Step 3: Create the Main Window
Every Tkinter application needs a main window. We create it using the Tk() class.
window = Tk()
window.title('Calculator')
window.geometry('235x318')
window.configure(bg=co1)Here is what each instruction does:
Tk()creates the main application window.title()defines the window title.geometry()sets the window dimensions.configure()changes the background color.
Our calculator window will have a width of 235 pixels and a height of 318 pixels.
Step 4: Organize the Interface Using Frames
Frames help us divide the application into smaller sections. For this calculator, we will use two frames: one for the display and another for the buttons.
frame_display = Frame(
window,
width=300,
height=56,
bg=co3
)
frame_display.grid(
row=1,
column=0,
sticky=NW
)
frame_buttons = Frame(
window,
width=300,
height=340,
bg=background
)
frame_buttons.grid(
row=2,
column=0,
sticky=NW
)The first frame will contain the calculator display, while the second will hold all the buttons.
We use the grid() geometry manager to position both frames inside the main window.
Step 5: Create the Calculator Functions
Before adding the buttons, we need to define the functions responsible for handling user input and calculations.
Our calculator will use three main functions.
1. Entering values
def entering_values(event):
global all_values
all_values += str(event)
value_text.set(all_values)This function receives a number or mathematical operator and adds it to the current expression.
For example, when the user presses 5, the value is added to the display. If the user then presses + and 3, the expression becomes 5+3.
2. Calculating the result
def calculate():
global all_values
try:
result = str(eval(all_values))
value_text.set(result)
all_values = ""
except:
value_text.set("Error")
all_values = ""The calculate() function evaluates the mathematical expression entered by the user.
We use Python's eval() function to evaluate the expression and display the result.
The try and except statements help handle errors that may occur when the expression cannot be evaluated.
Note: eval() should not be used directly with untrusted user input in production applications, as it can execute arbitrary Python expressions. For a more secure calculator, consider implementing a dedicated expression parser.
3. Clearing the display
def clear_screen():
global all_values
all_values = ""
value_text.set("")This function resets the calculator by clearing the current expression and removing its contents from the display.
Step 6: Create the Calculator Display
Now that the main functions are ready, we can create the display where numbers and calculation results will appear.
First, initialize the variable that will store the expression and create a StringVar() object.
all_values = ""
value_text = StringVar()Next, create the display using Tkinter's Label widget.
display = Label(
frame_display,
width=16,
height=2,
textvariable=value_text,
padx=7,
relief="flat",
anchor="e",
font=('Ivy 18 '),
bg='#37474F',
fg=co1
)
display.place(x=0, y=0)The textvariable parameter connects the label to our value_text variable. This allows the display to update whenever the value changes.
We also use anchor="e" to align the text to the right, which is a common layout for calculator displays.
Step 7: Add the Calculator Buttons
With the display ready, we can now create the buttons for numbers and mathematical operations.
Clear, Percentage, and Division Buttons
Let's start with the first row of buttons.
Button(
frame_buttons,
text="C",
width=11,
height=2,
bg=co10,
fg=background,
font=('Ivy 13 bold'),
relief=RAISED,
overrelief=RIDGE,
command=clear_screen
).place(x=0, y=0)
Button(
frame_buttons,
text="%",
width=5,
height=2,
bg=co10,
fg=background,
font=('Ivy 13 bold'),
relief=RAISED,
overrelief=RIDGE,
command=lambda: entering_values('%')
).place(x=118, y=0)
Button(
frame_buttons,
text="/",
width=5,
height=2,
bg=color1,
fg=co1,
font=('Ivy 13 bold'),
relief=RAISED,
overrelief=RIDGE,
command=lambda: entering_values('/')
).place(x=177, y=0)The first button clears the display, while the other two add the percentage and division operators to the expression.
Number Buttons
Instead of creating each number button individually, we can store their labels and positions in a list.
numbers = [
('7', 0, 52),
('8', 59, 52),
('9', 118, 52),
('4', 0, 104),
('5', 59, 104),
('6', 118, 104),
('1', 0, 156),
('2', 59, 156),
('3', 118, 156),
('0', 0, 208)
]
for num, x, y in numbers:
Button(
frame_buttons,
text=num,
width=5 if num != '0' else 11,
height=2,
bg=co10,
fg=background,
font=('Ivy 13 bold'),
relief=RAISED,
overrelief=RIDGE,
command=lambda n=num: entering_values(n)
).place(x=x, y=y)The numbers list contains three values for each button:
- The number displayed on the button.
- Its horizontal position (
x). - Its vertical position (
y).
We then use a for loop to create all the buttons automatically.
Notice the use of lambda n=num. This ensures that each button passes its own number when clicked, rather than referring to the same variable.
Mathematical Operators and Equals Button
Next, we create the remaining mathematical operators and the equals button.
operations = [
('*', 177, 52),
('-', 177, 104),
('+', 177, 156),
('.', 118, 208),
('=', 177, 208)
]
for op, x, y in operations:
Button(
frame_buttons,
text=op,
width=5,
height=2,
bg=color1 if op != '=' else color3,
fg=co1,
font=('Ivy 13 bold'),
relief=RAISED,
overrelief=RIDGE,
command=lambda o=op: entering_values(o) if o != '=' else calculate()
).place(x=x, y=y)Here, we use another loop to create the remaining buttons.
There is one important difference: when the user clicks an arithmetic operator, the entering_values() function is called. However, when the equals button is clicked, the calculate() function runs instead.
This allows us to handle different button actions without writing separate code for every button.
Step 8: Run the Application
We have now created the main window, display, buttons, and calculator functions.
The final step is to start the Tkinter event loop.
window.mainloop()The mainloop() method keeps the application running and listens for user interactions, such as button clicks.
Without it, the calculator window would open and immediately close.
Conclusion
In this tutorial, we built a simple calculator using Python and Tkinter. Along the way, we worked with windows, frames, labels, buttons, functions, loops, and event handling.
This is a practical beginner project because it brings together several Python fundamentals in a single application.
Once you understand how it works, you can experiment with additional features, such as keyboard support, improved error handling, calculation history, and a more advanced interface.
The best way to improve your programming skills is to keep building, experimenting, and solving small problems.
Keep learning Python and keep building projects.
📄 Copyright: Unless otherwise noted, all articles are original. Please cite the source when sharing.
🔗 Link: http://usandopy.com/en/projetos-em-python/como-criar-uma-calculadora-simples-em-python/