Sign in
Log inSign up

How to build a basic calculator with python

Robson's photo
Robson
·Sep 24, 2020·

6 min read

In this tutorial, we are going to build a very basic beginner friendly (BBF) calculator with Python.

Let's get started. Oh, We've already started. 😄

As usual, we need to import some modules from a library.

We only need tkinter. The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Creating a GUI application using Tkinter is relatively easy. All we need to do is to perfom the following steps;

  • Import the Tkinter module.
  • Create the GUI application main window.
  • Add some widgets to the GUI application.
  • Enter the main event loop to take action against each event triggered by the user.

Create a new file and name it whatever you want. I'll name mine calculator.py.

import tkinter as tk

The Tkinter module provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets.

Let's import some of this widgets that we'll use.

from tkinter import Label, Entry, Button

Now, we are going to create a window and give it a title. Windows are the containers in which all other GUI elements live. All our GUI elements that we've imported, such as entries, labels, and buttons, will be contained inside of the window.

#create a window
WINDOW = tk.Tk()
#give it a title
WINDOW.title('Python GUI Calculator')

so far so good.

Inside your file, your code should be looking like this.

# imports
import tkinter as tk
from tkinter import Label, Entry, Button

#create a window
WINDOW = tk.Tk()
#give it a title
WINDOW.title('Python GUI Calculator')

Before we run our program, let's add this line of code to our program.

WINDOW.mainloop()

window.mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or key-presses, and blocks any code that comes after it from running until the window it's called on is closed.If you don’t include window.mainloop() at the end of a program in a Python file, then the Tkinter application will never run, and nothing will be displayed.

Run calculator.py and see the output.

Ok, now we have our GUI setup; Let's add some widgets...

# create a label
label1 = Label(WINDOW, text="Enter first number ")

# create an entry
entry1 = Entry(WINDOW)

# repeat
label2 = Label(WINDOW, text="Enter first number ")
entry2 = Entry(WINDOW)

quick description of what is happening here. A Label is a widget used to display text on the screen. An entry is a text entry widget that allows only a single line of text.

We've created 2 GUI labels (label1 & label2) and 2 GUI entries(entry1 & entry2). All widgets are attached to the WINDOW. labels are given texts using the text attribute.

See how it is easy to create widgets, 😜

If we run our program, this widgets will not be displayed because they are not yet positioned in the WINDOW. We will position our widgets with the grid() method. grid() is a geometry manager. It works by splitting a window or Frame into rows and columns. You specify the location of a widget by calling .grid() and passing the row and column indices to the row and column keyword arguments, respectively. Both row and column indices start at 0, so a row index of 1 and a column index of 2 tells .grid() to place a widget in the third column of the second row.

# positioning widgets
label1.grid(row = 0, column = 0)
label2.grid(row = 2, column = 0)

entry1.grid(row = 0, column = 2)
entry2.grid(row = 2, column = 2)

Let's run calculator.py

Now we're definitely all set-up.

Next...

We're going to work with functions to perform our math operations. If you are new to python functions please checkout this great tutorial about python functions.

Let's create four functions;

  • add()
  • subtract()
  • divide()
  • multiply()

All this functions will be called upon clicking a button which is assigned a command attribute that points to the appropriate function. We will create this buttons later.

Quick tip;

We retrieve text from our entries using get() method.

We delete text with delete() method.

def add():
    """function to add two integers"""
    num1 = int(entry1.get())
    num2 = int(entry2.get())

    # results
    results = string(num1 + num2)

    # create a label to input results
    label3 = Label(WINDOW, text= result)
    # position label3
    label3.grid(row = 3, column = 2)

def subtract():
    """function to subtract two integers"""
    num1 = int(entry1.get())
    num2 = int(entry2.get())

    results = string(num1 - num2) # only the sign changed
    label3 = Label(WINDOW, text= result)
    label3.grid(row = 3, column = 2)

def divide():
    """function to divide two integers"""
    num1 = int(entry1.get())
    num2 = int(entry2.get())

    results = string(num1 / num2) # only the sign changed
    label3 = Label(WINDOW, text= result)
    label3.grid(row = 3, column = 2)

def multipy():
    """function to multipy two integers"""
    num1 = int(entry1.get())
    num2 = int(entry2.get())

    results = string(num1 * num2) # only the sign changed
    label3 = Label(WINDOW, text= result)
    label3.grid(row = 3, column = 2)

We also need to add two more functions. One clears our entries when called, another one helps us exit window.

def quit():
    """function to close the window """
    return WINDOW.destroy() # closes the Tkinter window

def clear():
    """ function to clear entries """
    entry1.delete(0, 'end') # clears entries from index 0 -> end
    entry2.delete(0, 'end')

We need to create two new buttons. One calls the clears function, another one calls the the quit function. We are also going to make use of the command attribute. Every Button widget has a command attribute that you can assign to a function. Whenever the button is pressed, the function is executed.

# create buttons, assign them to functions and position them
button1 = Button(WINDOW, text="clear", command=clear).grid(row =4, column =1)
button2 = Button(WINDOW, text="exit", command=quit).grid(row =4, column =2)

Finally, Let's create 4 more buttons

button one - Add numbers when clicked

button two - Subtract numbers when clicked

button three - Divide numbers when clicked

button four - Multiply numbers when clicked

button3 = Button(WINDOW, text="add", command=add).grid(row=3, column=3)
button4 = Button(WINDOW, text="subtract", command=subtract).grid(row=3, column=4)
button5 = Button(WINDOW, text="divide", command=divide).grid(row=3, column=5)
button6 = Button(WINDOW, text="multiply", command=multiply).grid(row=3, column=6)

That was it! Well, let's run our program and be ready to debug

"Huh, That was long! Just a calculator"? You might be thinking...! hmm.

We just learned how to use the tkinter module, create a basic GUI and built a calculator right away. Now go and improve that calculator and make it better. The final code for our calculator can be found Here.

Here is another great resource to learn more about tkinter

tkinter tutorial

Happy coding!


Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct