Loading, please wait...

A to Z Full Forms and Acronyms

Simple Calculator in Python using Tkinter | Part 1

Jul 16, 2020 Python, Tkinter, 11686 Views
This demonstrates how we can create a calculator GUI using tkinter in python .

How to create a simple calculator using TKINTER   PYTHON 3?

Through this article, we will learn how to create a simple calculator using Tkinter in python. For better understanding about the Tkinter module and the Tkinter widgets please read the article “How to create a simple registration form using Tkinter python3”.

Topics that we will discuss here are:

  • Tkinter widgets used for creating the calculator GUI.
  • Tkinter methods used for creating the calculator GUI.
  • Various attributes used for creating the calculator GUI.
  • Code for creating calculator GUI.
  • The output of the calculator GUI.

Tkinter widgets used for creating the calculator GUI.

  • Frame: This widget is basically used as a container to hold other widgets. Also, it is used to organize a group of widgets. This creates rectangular areas of the screen to organize the widgets to python application.

        Syntax to use this widget is:

   x = Frame(parent, options)

       where,

       options available are bd, bg, cursor, height,  highlightbackground , highlightcolor , highlightthickness , relief , width.

  • Entry: This widget provides a text box to the user. It accepts single-line string input from the user. This widget can only be used for one line of text from the user.

        Syntax to use this widget is: 

Y=Entry(parent, options)

        Where,

        Options available are bg , bd, cursor, exportselection, fg ,font , highlightbackground , highlightcolor , highlightthickness , insertbackground ,       insertborderwidth, insertofftime , insertontime , insertwidth, justify, relief, selectbackground,  selectborderwidth, selectforeground, show, textvariable , width ,xscrollcommand. 

  • Button: This widget is used to implement various types of buttons. It can contain images or text. Also, we can associate methods or functions with buttons. When a click event occurs on button Tkinter automatically calls the functions or method.

        Syntax to use this widget:

z= Button(parent,options)

        where options available are bd, bg, fg, command, font, height, image, justify, padx, pady, activebackground, activeforeground, highlightcolor, relief,state,  underline, wraplength.

Tkinter methods used for creating the calculator  GUI.

  • get(): This is a standard Tkinter method that is used to get the written text inside the widget.
        Example: scvalue.get()              # This accepts the input scvalue.
  • eval(): This is a built-in function it returns the result as an integer. This parses the expressions “String” arguments as python expression.
        Example:  value= eval(scvalue.get())          #This will evaluate the obtained scvalue.
  • update(): This method is used to update the changes.
        Example:
screen.update()               #This will update the screen with latest value.​
  • set(): This method is used to set and change the value stored within the Tkinter variable.
        Example: scvalue.set(scvalue.get() +text)               
  • StringVar(): This is a class used to monitor changes to the Tkinter variable. We can create an instance of it to use it.

        Example:

sc=StringVar()       #This holds a string and by default it holds “”
  • pack(): This method with the screen is used to organize the geometry of widget in blocks after placing in parent widget i.e it act as a geometry manager.
        Example: screen.pack(fill=X, ipadx=8, padx=10, pady=10)
  • bind(): To deal with events, we need to bind python functions and methods.
        Example: b.bind("<Button-1>", click)
  • mainloop(): This is like infinite loop used to run the application. It basically waits for an event to occur as long as the window is not closed.
        Example: root.mainloop()
  • title(): This is used with the instance of Tk() to provide the title to the window.
        Example: root.title(" SIMPLE CALCULATOR ")
  • geometry(): This is used with the instance of Tk() to provide the dimension to the window.
        Example: root.geometry("644x700")
  • Tk():It is GUI toolkit available on windows system as well as mostunix platforms. There are many GUI toolkit available but it is used mostly for development of GUI application.
        Example: root = Tk()

Various attributes used for creating the calculator GUI.

  • side: This defines the direction of the widget while packing widget.
  • ipadx, ipady: This defines a number of pixels to pad widget, horizontally, and vertically. But only inside the widget’s border.
  • padx, pady: This defines the number of pixels to pad widget, horizontally, and vertically. But only inside the widget’s border.
  • font: This is used to define the font type and size.
  • bg: To set the background color.
  • textvar: It associates a Tkinter variable to the content of the entry field.

Code for creating a calculator:

#importing all files from tkinter
from tkinter import *

#defining the height and width of button
button_height=1
button_width=3

#This Defines the function for click event
def click(event):
    global scvalue      #Global variable "scvalue"
    text = event = event.widget.cget("text")
    print(text)
    #This will check if the input text from user is "="
    if text == "=":
        #this will check if the scvalue is a digit or not
        if scvalue.get().isdigit():
            #this will evaluate the string value like if we type 7*8 it will give 56 as result.
            value= eval(scvalue.get())
        else:
            try:
              value= eval(scvalue.get())
            except Exception as e:
                print(e)
                value="ERROR"

        scvalue.set(value)
        screen.update()
    elif text == "C":
        pass
    else:
        scvalue.set(scvalue.get() +text)  # this will combine the value of scvalue and text
        screen.update()  # It force updation

#It creates tkinter window or root window
root = Tk()
#Defining the geometry of the root or tkinter window
root.geometry("644x700")
#Defining the title of root or tkinker window
root.title(" SIMPLE CALCULATOR ")

#this define "scvalue" as String variable (Note: It is a global variable )
scvalue = StringVar()
#set() method is used to set and change the value stored within a tkinter variable here the variable is "scvalue"
scvalue.set("")
#Entry widget is used to accept the single line input from the user.
screen = Entry(root, textvar=scvalue, font="lucida 20 bold")
#pack() method with screen is used to organize the geometry of widget in blocks after placing in parent widget.i.e it act as a geometry manager
screen.pack(fill=X, ipadx=8, padx=10, pady=10)


#Frame for first row
#Frame widget to create container to hold other widgets (here it is holding Button widget)
f = Frame(root, bg="grey")
b = Button(f, text="9", padx=28, pady=18, font="lucida 20 bold")  #Button Widget
b.pack(side=LEFT, padx=18, pady=5)    #packing button widget
b.bind("<Button-1>", click)           #binding function to the event "CLICK"

b = Button(f, text="8", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="7", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack() #pack() method to organize the geometry of object "f" of Frame widget


#Frame for second row
f = Frame(root, bg="grey")
b = Button(f, text="6", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="5", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="4", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack()


#Frame for third row
f = Frame(root, bg="grey")
b = Button(f, text="3", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="2", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="1", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack()


#Frame for fourth row
f = Frame(root, bg="grey")
b = Button(f, text="-", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="0", padx=30, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="+", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack()


#Frame for fifth row
f = Frame(root, bg="grey")
b = Button(f, text="/", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="C", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

b = Button(f, text="=", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack()

#Frame for sixth row
f= Frame(root, bg="grey")
b = Button(f, text="%", padx=30, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)


b = Button(f,text="*", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)


b = Button(f,text=".", padx=28, pady=18, font="lucida 20 bold")
b.pack(side=LEFT, padx=18, pady=5)
b.bind("<Button-1>", click)

f.pack()

#running mainloop
root.mainloop()

 The output of the calculator GUI:

Hope you like this article, In this article, I used simple codes without any loops so that beginners can also understand all the lines of code. We can optimize the same code using loops and functions. So try to optimize the code. In the upcoming article, I will share how we can optimize this code.

If you find it useful do share it with your friends.

So till now

Happy Learning.😊😊

A to Z Full Forms and Acronyms

Related Article