Best Python Projects for Kids in 2021: How to make a calculator with Tkinter

In this lesson, we are going to be creating a simple calculator program using Tkinter. Although the project may sound hard at first, it’s simple once you understand what to do, so let’s get started! This is an Beginner-level project for those who are new to Python. Especially for students who have completed Python Level 1, At this point, you should already know the basics of how to use Tkinter and lambda functions. And have built strong knowledge in Python basics such as creating functions and variables. This project focuses on using lambda functions as well as creating a functional GUI (Graphical User Interface)for the program.

Table Of Content:

This project can be broken down into 4 main steps:

  1. Setup
  2. Function Definition
  3. Expression Field formatting
  4. Button formatting

1. Setup

First, we’ll start by setting up Tkinter. We do this by typing

from tkinter import *

Next, we will need to create our expression variable. This is the variable that the buttons will control, and will be what gives us the final result. To do this we type:

expression = ""

Once we’ve imported Tkinter and have set up our expression variable, we can define our functions. Each function will control an action the code will execute when the function is called.For this project, we will have three main functions:

  1. press(num)
  2. equalpress()
  3. clear()

2. Function Definition

Let’s start by defining the press(num) function:

def press(num):
   global expression
   expression = expression + str(num)
   equation.set(expression)

Note that we’ve defined ‘expression’ as global. This means that we will be able to use it anywhere - both inside and outside of functions.

Next we’ll go ahead and define our equalpress() function:

 def equalpress():
   # Try and except statement is used to handle errors
   try:
       global expression
       #will calculate the result and make it a string
       total = str(eval(expression))
       equation.set(total)
       #set the expression to empty
       expression = ""
   #if there is an error, the error message will be displayed
   except:
       equation.set(" error ")
       expression = "" 

Finally, we’ll define our clear function. All this will do is set the expression to an empty string when the button is pressed.

def clear():
   global expression
   expression = ""
   equation.set("")

3. Expression Field Formatting

Now that we’re done defining all our functions, we can start formatting the calculator’s GUI.  To start, we’ll create the GUI window (this will be the window where the calculator shows up), and set its dimensions. We will also prevent the window from being resized, which would mess up the alignment of the buttons. I’ve also added a line at the end to set the background colour to a dark grey colour. This will create more contrast between the buttons and the background of the window. At the end the code should look like this:

if __name__ == "__main__":
   # create a GUI window
   gui = Tk()
   # set the dimensions and title of GUI window
   gui.geometry("385x180")
   gui.title("Simple Calculator")
   #stop the window from being resized and messing up the layout
   gui.resizable(0, 0)
   # set the background colour of GUI window
   gui.configure(background="snow2")

Once the calculator window has been created, we need to make the expression field. This is the part of the window where the expression will show up. Here's how we'll do it:

#create a StringVar class
   equation = StringVar()
   #this will create the box where the expression and solution will be displayed
   expression_field = Entry(gui, textvariable=equation)

  # create the expression box/sizing
   expression_field.grid(columnspan=4, ipadx=100)

Note that at the beginning we defined the expression as a StringVar. This is a Tkinter function that will allow us to monitor any changes to the variable if needed. Now that the second step is complete.

4. Button Formatting

It’s time to add the buttons. To do this, we will need to create the button name variable and set it to a button, then we can add the visual components. We will be adding text and colours, setting the buttons' height and width, and adding lambda commands to control the buttons. On the next line, we will place the button by using the .grid command to specify which row and column it will be in. You may want to decide where you want each button before beginning to code, as it will make deciding where to place each button in much easier. After the first button’s code is finished, it should look something like this:

button1 = Button(gui, text=' 1 ', fg='black', bg='gray65', 
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)

To make things easier, after the first button is done, you can copy and paste the code to create the other buttons. All you need to do from there is change the symbols that show up and the numbers in the press() function. In the end, we will have:

button2 = Button(gui, text=' 2 ', fg='black', bg='gray65',
                   command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='gray65',
                   command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='gray65',
                   command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='gray65',
                   command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='gray65',
                   command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='gray65',
                   command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='gray65',
                   command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='gray65',
                   command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='gray65',
                  command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)

And also the operators buttons:

plus = Button(gui, text=' + ', fg='black', bg='gray65',
               command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='gray65',
               command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='gray65',
                   command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='gray65',
                   command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)
Decimal= Button(gui, text='.', fg='black', bg='gray65',
               command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=5, column='1')

Now that most of the number and operations buttons are complete, we have only 2 more buttons left to code! Because we defined equal and clear as functions in the beginning, they will have command= function name  instead of command= lambda. Other than that minor difference, they’ll be the same as the rest of the buttons. I will let new students know how can we do without lambda function, so in the end the code should look like this:

equal = Button(gui, text=' = ', fg='black', bg='gray65',
              command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='gray65',
               command=clear, height=1, width=7,)
clear.grid(row=6, column=0, columnspan = 4)

Finally, we need to add the line of code that will start the GUI. To do this, the code will be:

gui.mainloop()

And now we’re done! Feel free to test your code and see how it works!

Kelsey is a Grade 10 student in Ontario, Canada. She completed Python, Java, and C++ at Geekedu. She is now focused on preparing for the USACO Silver Competition. She dreams of studying at MIT and is dedicated to turning that dream into reality step-by-step. Kelsey loves to write tutorials as a way to share her learning experience with Geekedu.

Sign up and get a 60-minute free assessment class

Book A FREE Trial