Python Calculator – Create A Simple GUI Calculator Using Tkinter

A Simple GUI Calculator in Python Thumbnail

How are you, Python developers? You will learn how to create a simple graphical user interface calculator in this tutorial. I’ll show you how to create a simple calculator in Python using the tkinter module in this post. As a result, let us begin by developing a simple Python calculator.

Python provides numerous options for creating graphical user interfaces, but Tkinter is the most useful module (Graphical User Interface). Tkinter is a cross-platform application that runs on Windows and Linux. As a result, I wrote a simple Python calculator that makes use of the Tkinter module.

Introduction to Python Calculator – Getting Started With Tkinter

The quickest and easiest way to develop graphical user interfaces in Python is to use Tkinter. Therefore, let us take a quick look at Tkinter.

What exactly is Tkinter?

Tkinter (“Tk interface”) is the standard Python interface to the Tk toolkit for creating graphical user interfaces.
Both Tk and Tkinter are available for the majority of Unix-like platforms as well as Windows.
If you use Linux/Ubuntu, you must install the Tkinter module; however, if you use Windows, you do not need to install it because it is included in the default Python installation.

Python Calculator Prerequisite

To develop a simple graphical user interface calculator in Python, the following prerequisite knowledge is required:

The Appearance Of A Simple Python GUI Calculator

Consider the calculator below. Indeed, this appears to be quite cool. As a result, we now need to create a Python calculator.

Py Calcalator Final

We can perform the following simple mathematical calculations on this calculator –

  • Multiplication
  • Addition
  • Subtraction
  • Division

And now we’ll begin writing the code necessary to create this. To accomplish this, we must complete four steps –

  • Tkinter module import
  • Developing the primary interface (window for calculator)
  • Adding as many widgets as desired to the main interface
  • Utilizing widgets as event triggers

If Necessary: To install the Tkinter module, run the following command below:

				
					pip install tkinter
				
			

Creating A Calculator Window

We’ll begin by creating a calculator window. The following code should be printed as a result.

				
					from tkinter import *

# Creating frame for calculator


def iCalc(source, side):
    storeObj = Frame(source, borderwidth=4, bd=4, bg="powder blue")
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj

# Creating Button


def button(source, side, text, command=None):
    storeObj = Button(source, text=text, command=command)
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj


class app(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'arial 20 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Calculator')


# Start the GUI
if __name__ == '__main__':
    app().mainloop()

				
			

We have created this frame successfully; now let us proceed.

Integrating a Display Widget

Create a display widget by writing the following code inside the class app.

				
					display = StringVar()
        Entry(self, relief=RIDGE, textvariable=display,
          justify='right'
          , bd=30, bg="powder blue").pack(side=TOP,
                                          expand=YES, fill=BOTH)
				
			

Including a Widget for Clear Button

Now we’ll create a clear button. This button clears the contents of the display when pressed. As a result, write the following code to achieve this.

				
					        for clearButton in (["C"]):
            erase = iCalc(self, TOP)
            for ichar in clearButton:
                button(erase, LEFT, ichar, lambda
                    storeObj=display, q=ichar: storeObj.set(''))
				
			

Widget for Adding Numbers And Symbols

To include numbers and symbols within the frame, you must write the following code.

				
					         for numButton in ("789/", "456*", "123-", "0.+"):
         FunctionNum = iCalc(self, TOP)
         for iEquals in numButton:
            button(FunctionNum, LEFT, iEquals, lambda
                storeObj=display, q=iEquals: storeObj
                   .set(storeObj.get() + q))
 
				
			

Including an Equal Button

Create the Equal button using the following code.

				
					EqualButton = iCalc(self, TOP)
for iEquals in "=":
        if iEquals == '=':
            btniEquals = button(EqualButton, LEFT, iEquals)
            btniEquals.bind('<ButtonRelease-1>', lambda e, s=self,
                            storeObj=display: s.calc(storeObj), '+')

        else:
            btniEquals = button(EqualButton, LEFT, iEquals,
                                lambda storeObj=display, s=' %s ' % iEquals: storeObj.set
                                (storeObj.get() + s))

				
			

Using Event Triggers With Widgets

Finally, but certainly not least, is the use of widgets with event triggers. This means that when you click on a widget, it executes a function. As a result, write the following code.

				
					    def calc(self, display):
            try:
                display.set(eval(display.get()))
            except:
                display.set("ERROR")
				
			

Complete Python Calculator Code

As a result, I’m now compiling and storing all of the codes mentioned above in a single location. As a result, we’ve included the complete Python code for creating a simple calculator below.

				
					from tkinter import *


def iCalc(source, side):
    storeObj = Frame(source, borderwidth=4, bd=4, bg="powder blue")
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj


def button(source, side, text, command=None):
    storeObj = Button(source, text=text, command=command)
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj


class app(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'arial 20 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('IAMNK Calculator')

        display = StringVar()
        Entry(self, relief=RIDGE, textvariable=display,
              justify='right', bd=30, bg="powder blue").pack(side=TOP,
                                                             expand=YES, fill=BOTH)

        for clearButton in (["C"]):
            erase = iCalc(self, TOP)
            for ichar in clearButton:
                button(erase, LEFT, ichar, lambda
                       storeObj=display, q=ichar: storeObj.set(''))

        for numButton in ("789/", "456*", "123-", "0.+"):
            FunctionNum = iCalc(self, TOP)
            for iEquals in numButton:
                button(FunctionNum, LEFT, iEquals, lambda
                       storeObj=display, q=iEquals: storeObj
                       .set(storeObj.get() + q))

        EqualButton = iCalc(self, TOP)
        for iEquals in "=":
            if iEquals == '=':
                btniEquals = button(EqualButton, LEFT, iEquals)
                btniEquals.bind('<ButtonRelease-1>', lambda e, s=self,
                                storeObj=display: s.calc(storeObj), '+')

            else:
                btniEquals = button(EqualButton, LEFT, iEquals,
                                    lambda storeObj=display, s=' %s ' % iEquals: storeObj.set
                                    (storeObj.get() + s))

    def calc(self, display):
        try:
            display.set(eval(display.get()))
        except:
            display.set("ERROR")


if __name__ == '__main__':
    app().mainloop()

				
			

Now it’s time to look at the calculator, which you can use to perform any operation. Therefore, let us begin your calculation.

Py Calcalator Final

Congratulations, We succeeded in creating a Python calculator, which is quite cool, and I hope you enjoyed the process. Therefore, if you enjoy this, please express your thoughts and follow me on YouTube, Facebook, Twitter, and LinkedIn. Don’t forget to subscribe to my channel by clicking the bell icon.