Coders Packet

Build a simple Calculator - Python GUI (tkinter)

By KURVA ASHOK KUMAR

In this post, you will be learning how to create a graphical user interface with Python and Tkinter and also you will learn how to build a simple calculator app!

1. Creating graphical user interface with Python:

We are going to create a graphical user interface in Python using tkinter module that comes built in with Python that helps you to create GUI's relatively easy and very quickly. To understand the topic you need to know the basics of Python programming language and you need to install Python in your pc. That's not a very tough task to perform. I'll drop down a link here to download Python down here. Based on your operating system, dowload and install Python in your pc na dthen you are all set to go ahead in building a calculator:

To start we need to import tkinter:

from tkinter import *

In tkinter everything is a widget,there is button widgets,text widgets,frame widgets and the first thing you are going to create is the root widget(think of it like the window(box)).Here you are going to create a simple hello world window:

from tkinter import *
#in tkinter everything is a widget.Let's create a widget first
root=Tk()
#creating a label widget and we should put this label widget 
#into root widget
myLabel=Label(root,text="Hello World!")
myLabel.pack()
root.mainloop()

For this you need to create a label widget and you need to put this label in your root. To place a label widget into your root you need to use "labelname.pack()" method.In tkinter creating a widget is basically a two step process.One is defining a widget and the next is placing(packing) this widget into the root widget.The last thing you have to do is the creating an event loop.When you have a graphical user interface when you have a program running it's always looping constantly and that's how it figures out what's going on.To do that we want to type root.mainloop() because this is the main loop of the program.

2.Creating Buttons:

It is same as creatinng a label widget.The only difference you will be noticing in code is that you will define a function to tell to the machine about the instructions to be perfoormed when you click on that button:

from tkinter import *
root=Tk()
def myClick():
    myLabel=Label(root,text='Look! I clicked the button')
    myLabel.pack()
myButton=Button(root,text='Submit',state='active',padx=5,pady=5,command=myClick,fg="white",bg='black')
myButton.pack()
root.mainloop()

3. Creating Input fields:

It is same as creatinng a label widget.Instead of using a label () method over there we use Entry().

from tkinter import *
root=Tk()
e=Entry(root,width=50,borderwidth=5)
e.pack()
def myClick():
    myLabel=Label(root,text=e.get())
    myLabel.pack()
myButton=Button(root,text='Submit',state='active',padx=5,pady=5,command=myClick)
myButton.pack()
root.mainloop()

4.Build A Simple Calculator:

from tkinter import *
root=Tk()
root.title("Simple Calculator")
e=Entry(root,width=50,borderwidth=5)
e.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
def button_click(number):
    curr=e.get()
    e.delete(0,END)
    e.insert(0,str(curr)+str(number))
    return
def button_clear():
    e.delete(0,END)
    return
def button_add():
    first_number=e.get()
    global f_num
    global math
    math='addition'
    f_num=int(first_number)
    e.delete(0,END)
def button_sub():
    first_number=e.get()
    global f_num
    global math
    math='subtraction'
    f_num=int(first_number)
    e.delete(0,END)
def button_mul():
    first_number=e.get()
    global f_num
    global math
    math='multiplication'
    f_num=int(first_number)
    e.delete(0,END)
def button_div():
    first_number=e.get()
    global f_num
    global math
    math='division'
    f_num=int(first_number)
    e.delete(0,END) 
def button_equal():
    second_number=e.get()
    e.delete(0,END)
    if math=='addition':
        e.insert(0,f_num + int(second_number))
    elif math=='subtraction':
        e.insert(0,f_num - int(second_number))
    elif math=='multiplication':
        e.insert(0,f_num * int(second_number))
    elif math=='division':
        e.insert(0,f_num / int(second_number))
    
button_1=Button(root,text="1",padx=45,pady=20,command=lambda:button_click(1))
button_2=Button(root,text="2",padx=48,pady=20,command=lambda:button_click(2))
button_3=Button(root,text="3",padx=45,pady=20,command=lambda:button_click(3))
button_4=Button(root,text="4",padx=45,pady=20,command=lambda:button_click(4))
button_5=Button(root,text="5",padx=48,pady=20,command=lambda:button_click(5))
button_6=Button(root,text="6",padx=45,pady=20,command=lambda:button_click(6))
button_7=Button(root,text="7",padx=45,pady=20,command=lambda:button_click(7))
button_8=Button(root,text="8",padx=48,pady=20,command=lambda:button_click(8))
button_9=Button(root,text="9",padx=45,pady=20,command=lambda:button_click(9))
button_0=Button(root,text="0",padx=45,pady=20,command=lambda:button_click(0))
button_add=Button(root,text="+",padx=44,pady=20,command=button_add)
button_sub=Button(root,text="-",padx=45,pady=20,command=button_sub)
button_mul=Button(root,text="*",padx=48,pady=20,command=button_mul)
button_div=Button(root,text="/",padx=45,pady=20,command=button_div)
button_equal=Button(root,text="=",padx=101,pady=20,command=button_equal)
button_clear=Button(root,text="Clear",padx=91,pady=20,command=button_clear)

button_1.grid(row=3,column=0)
button_2.grid(row=3,column=1)
button_3.grid(row=3,column=2)

button_4.grid(row=2,column=0)
button_5.grid(row=2,column=1)
button_6.grid(row=2,column=2)

button_7.grid(row=1,column=0)
button_8.grid(row=1,column=1)
button_9.grid(row=1,column=2)

button_0.grid(row=4,column=0)
button_clear.grid(row=4,column=1,columnspan=2)
button_add.grid(row=5,column=0)
button_equal.grid(row=5,column=1,columnspan=2)

button_sub.grid(row=6,column=0)
button_mul.grid(row=6,column=1)
button_div.grid(row=6,column=2)
root.mainloop()

Explanation of the code:

As you are aware first we are importing tkinter module and creating a root window for our calculator  and then we create a textfield. e.grid() does the positioning of the textfield i..e.,the box where we are going to type our numbers for doing certain airthmetic operations.Column span indicates the number of columns does a text fiels should cover.Then we go on add buttons from 0 to 9 and also the addition, subtratction,multiplication,division,equal,clear button.Using the grid() method we position them at the correct place and while defining the buttons we see to it that they correctly fit into the root widget providing suitable padx and pady values as arguements in button defination. 

After defining the buttons and positioning them into the root widget we now define functions for performing the required operations when we click a button.

Now if we run our program, we will able to see the a simple calculator and perform basic Airthmetic operations.

Hope this post helps you understand the concept of GUI and the usage of tkinter module in Python.

Download Complete Code

Comments

No comments yet