Built Simple GUI Calculator using Tkinter Python Library | Python Projects

Hello and welcome, In this tutorial, we are going to build a simple calculator using the Python Tkinter module. we will also add some additional features to make it look attractive, amazing, and useful. Tkinter is a built-in Python module for creating GUI applications. It is easy to use and comes with python, no need to install it separately.

Built simple Calculator using Python Tkinter Library

As in our previous tutorial we have created a Dice Simulator using Tkinter in Python. If you do not have a basic knowledge of Tkinter then please visit this project where you will have a deep understanding of the GUI application, and you will be able to work with Tkinter. This Project contains a little bit of advancement compared to that because we are going to explore Tkinter to the next level.

The Python Calculator which we are going to build will look something like this: 

Python Calculator using Tkinter

Hands-on Building GUI Calculator using Python from Scratch

Create a new Python File named "calculator.py" in your favorite python IDE whether it may be PyCharm, Spyder, VS-code, etc. You can name a file as per your preference and now let us get to the coding of a calculator.

Step-1) Import Libraries

The first step is to import the necessary libraries. so, we are going to import Tkinter, a parser for parsing the string, and some functions from the math module which will help perform some operations in a calculator.
from tkinter import *
from math import factorial
import parser

Step-2) Make a top-level widget for your Calculator

Generating a top-level widget is very simple using Tkinter and can be made using the following steps. It is a simple Tkinter initial GUI blank window where we will be creating a calculator. 
#make a top level tkinter window for our calculator
root = Tk()

# set the background color of your gui
root.configure(background="light blue")
root.geometry('300x180')
root.title('Crazy_Tech Calculator')

The above code will make a blank window for your calculator with the title "Crazy_Tech Calculator". 

  • Geometry:- Geometry is used to set the calculator window geometry of particular width and height. 
  • configure:- configure method is used to have some custom configuration to GUI window. here we have added a background color as light blue to make the calculator look attractive.
  • mainloop:- Call the main event loop so that actions can take place on the user's computer screen. It means when you want to run the program and see the output write the below single line of code in last to call the main function and let the output screen be visible till you close it.
#call the mainloop to run code
root.mainloop()

Step-3) Designing a Buttons

Now, let's build Buttons for the Calculator and put them on the main window. First, we will create an empty field where all the calculations will happen(Calculator Screen). Then, we will add all the buttons using the grid geometry method of Tkinter. Let us take a brief overview of Grid geometry and its purpose.

Python Tkinter grid() method                                                                           

The grid() geometry manages all the widgets in a tabular form. We can specify rows and columns as a parameter during a method call as well we can also specify rowspan(height) or colspan(width) of a widget. It is a more organized way to place a Widget on a Python application.

let's create a button, if some of the attributes you are not capable to get then they are explained below the code snippet.

Explanation ~ As we saw in the above demo image we have 4 rows containing keys and a final row to see the output. First, we have added four rows in which the top 3 rows have digits 1 to 9 and zero. The fourth row has control buttons. Then we add operators columns wise forward to these rows. Now, what functions we have used to create this is explained in the below paragraph. 

In this Calculator program, the Entry function helps in making an input field(calculator screen) and we use the Button method to display a button. We used a .grid() method to position the buttons accurately on the screen. We have also used a Label method to leave a blank line before displaying a calculator to make it look quite attractive.

  • root:- name through which we refer our main window
  • text:- text to be displayed on the button
  • row:- index of a row which is positioned using the grid method.
  • column:- column index set with grid method
  • active background:- attribute to change the color of the button when clicked.
  • fg and bg:- attribute for font color and background color.
  • columnspan:- combines the number of columns
  • sticky:- If the resulting cell is larger than a widget then sticky defines how to expand a widget. By defining this parameter widget is centered in its cell. Sticky can be defined as a combination of a string of zero or N, E, S, W or NW, NE, SW, SE are analogous to the directions in compass. N+E+W+S means that the widget should expand in all directions.
  • Command:- Command is a parameter used to make an action when a button is pressed. we have added a function call that corresponds to each button.

NOTE:

If you have noticed an error after running this above code as, no function get_variable() or get_operation() found, then do not worry. we are now going to assign the functionality of each button we have used. till now we have only declared the functions, hence you are receiving an error. let's quickly define them and map each button functionality.


Step-4) Mapping Buttons to their Functionalities

Now we have created the buttons but when I click them nothing happens so we have to provide it a functionality so that whenever we click on any key respective operation should happen. You have to write this function above the code where we have created buttons means below display field line.

👉 Mapping the digits with get_variable() method

This is a function that helps display digits on the output screen. Whenever we click on any digit it should appear on the screen. we have provided its functionality in the command attribute when we have created buttons.

# declare var which will keep track of current pos on the input text field
i = 0

#recieve digit as parameter and display on input field
def get_variable(num):
    global i
    display.insert(i,num)
    i += 1  
The get_variable method takes a digit as parameter input. the digit is inserted into the input field using the insert function with parameters i and num. I keep the position of input where a digit is being inserted. The global variable i updates each time to insert the next digit or next operator. In this way, it forms a complete expression on the input-output screen.

👉 Mapping the operator buttons

The same we have to do with operators like when any operator key is pressed then it should appear on the screen. The reason to create a separate function for this is that some operators have lengths greater than 1 so we have to move the global position variable by operator length.

#mapping operator buttons
def get_operation(operator):
    global i
    length = len(operator)
    display.insert(i,operator)
    i += length
The get_operation function receives the operator as an input parameter and displays it on the input field with the insert method.

👉 Mapping the AC button to clear the screen 

AC button helps in clearing the screen and that's what we have to do.

#map AC button(clear screen)
def clear_all():
    display.delete(0,END)

We use the delete method to delete the characters from an input field. It takes the start and end position, so we have cleared the entire screen.

👉 Mapping the undo(<-) button 

Undo button is helpful to remove the last operator or digit inserted on the input screen. It's equal to ctrl+z operation in laptops.

def undo():
    entire_string = display.get()
    if len(entire_string):
        new_string = entire_string[:-1]
        clear_all()
        display.insert(0, new_string)
    else:
        clear_all()
        display.insert(0,"Error")

Explanation ~ The undo functions take the entire digits and operator from the input field using the get() method and generated the new string except for the last char of the old string if the string len is positive. And it clears the screen and inserts the new string with 1 char less and updates the input field. And if an input field is empty and we try to use this command then it displays an error.

👉Mapping the factorial (!) button 

We have also added a factorial functionality so when we click it then we should get the respective factorial. The code is in a try-catch block to avoid any kind of exeptions.

def fact():
    entire_string = display.get()
    try:
        result = factorial(int(entire_string))
        clear_all()
        display.insert(0, result)
    except Exception:
        clear_all()
        display.insert(0,"Error")

We fetch the string from the input field. we convert the string to int and pass it to factorial function which we have imported from the math module in beginning. After that, we clear the input field and updates the result of factorial. We also deal with an exception by clearing the input field and passing the error message if anything goes wrong in the input field.

👉 Mapping the Calculate "=" button 

The final function is the output (assignment) function to get the output. We only have to evaluate the complete expression on the input screen and display the final computed output.

def calculate():
    entire_string = display.get()
    try:
        a = parser.expr(entire_string).compile()
        result = eval(a)
        clear_all()
        display.insert(0, result)
    except Exception:
        clear_all()
        display.insert(0, "Error")

Explanation ~ we fetch the string from the input field using the .get() method. we make the use to parse module to scan the string using the expr() method which accepts a string as a parameter. we basically leave it to the parser to build an abstract syntax tree of string which is being evaluated by the eval() function.

Final Screen of Python Calculator

If not then add the mainloop line at the end and execute the program, you will able to see the output screen with a calculator and all the functions are correctly working.



Complete Source code can be found here: GUI Calculator in Python

Summary

Yay! ✌ We have successfully designed a Python Calculator using Tkinter. It was an amazing experience and learning during this simple project. Now, that you have a better understanding of the Tkinter works and capable to work with them. Try to explore it more and what features you can add to this calculator and designs to make it look more attractive like add a justify parameter to the input field to take input from the right side or add a log function.


👉 For more Python Projects Explore the tab: Python Projects for beginners
Thank you!..

2 Comments

If you have any doubt or suggestions then, please let me know.

  1. ����

    ReplyDelete
  2. great bro , just a small program for better initiation of GUI programming with python.....great to learn from TKinter library

    ReplyDelete
Previous Post Next Post