How to make a gui Calculator in Python using Tkinter

I have written a basic & simple GUI calculator in python using Tkinter module. Since Tkinter is cross-platform so it works on both windows and Linux. If you are a beginner, and want to learn some basic GUI with python, this will be helpful for you.

calculator

you can download the program HERE
or, you can clone it from my github repository

In order to run the program on ubuntu/linux you must have Tkinter module installed. 

in windows, You don’t need to install Tkinter as it comes with the default python installation.

For Ubunt/Debian/Linux Mint.
Install Tkinter by entering this command.

sudo apt-get install python-tk

Basic Idea of this calculator

When any number (0,1,2…) or operator (+,-,*,/,%) button is pressed, its value is passed to the action function, where the value is simply inserted into the text box of the calculator.

and when the ‘=’ button is pressed the equal function is called, where the expression in text box is stored in a variable expression and the result is calculated using the eval function.

The square, square root, modulus function work similarly to the equal function, the only difference being it uses math functions to calculate square,square root… after evaluating the expression.

Before doing the evaluation we replace ÷ with / and x with * in the getandreplace function. we also check if the user has entered the expression in the correct syntax using the ‘try-except‘ block.

The use of Tkinter here

First, we create an object named root out of Tk  (Note the capitalization of Tk)
we create an object of the calc and pass root as master to the init method.

mainloop starts an event loop, which is basically an infinite loop waiting for events and respond accordingly. The mainloop can be terminated by closing the window or using the close method.

#-*-coding: utf-8-*-
from Tkinter import *
import math

class calc:
 def getandreplace(self):
  """replace x with * and ÷ with /"""
  
  self.expression = self.e.get()
  self.newtext=self.expression.replace(self.newdiv,'/')
  self.newtext=self.newtext.replace('x','*')

 def equals(self):
  """when the equal button is pressed"""

  self.getandreplace()
  try: 
   self.value= eval(self.newtext) #evaluate the expression using the eval function
  except SyntaxError or NameErrror:
   self.e.delete(0,END)
   self.e.insert(0,'Invalid Input!')
  else:
   self.e.delete(0,END)
   self.e.insert(0,self.value)
 
 def squareroot(self):
  """squareroot method"""
  
  self.getandreplace()
  try: 
   self.value= eval(self.newtext) #evaluate the expression using the eval function
  except SyntaxError or NameErrror:
   self.e.delete(0,END)
   self.e.insert(0,'Invalid Input!')
  else:
   self.sqrtval=math.sqrt(self.value)
   self.e.delete(0,END)
   self.e.insert(0,self.sqrtval)

 def square(self):
  """square method"""
  
  self.getandreplace()
  try: 
   self.value= eval(self.newtext) #evaluate the expression using the eval function
  except SyntaxError or NameErrror:
   self.e.delete(0,END)
   self.e.insert(0,'Invalid Input!')
  else:
   self.sqval=math.pow(self.value,2)
   self.e.delete(0,END)
   self.e.insert(0,self.sqval)
 
 def clearall(self): 
  """when clear button is pressed,clears the text input area"""
  self.e.delete(0,END)
 
 def clear1(self):
  self.txt=self.e.get()[:-1]
  self.e.delete(0,END)
  self.e.insert(0,self.txt)

 def action(self,argi): 
  """pressed button's value is inserted into the end of the text area"""
  self.e.insert(END,argi)
 
 def __init__(self,master):
  """Constructor method"""
  master.title('Calulator') 
  master.geometry()
  self.e = Entry(master)
  self.e.grid(row=0,column=0,columnspan=6,pady=3)
  self.e.focus_set() #Sets focus on the input text area
    
  self.div='÷'
  self.newdiv=self.div.decode('utf-8')

  #Generating Buttons
  Button(master,text="=",width=10,command=lambda:self.equals()).grid(row=4, column=4,columnspan=2)
  Button(master,text='AC',width=3,command=lambda:self.clearall()).grid(row=1, column=4)
  Button(master,text='C',width=3,command=lambda:self.clear1()).grid(row=1, column=5)
  Button(master,text="+",width=3,command=lambda:self.action('+')).grid(row=4, column=3)
  Button(master,text="x",width=3,command=lambda:self.action('x')).grid(row=2, column=3)
  Button(master,text="-",width=3,command=lambda:self.action('-')).grid(row=3, column=3)
  Button(master,text="÷",width=3,command=lambda:self.action(self.newdiv)).grid(row=1, column=3) 
  Button(master,text="%",width=3,command=lambda:self.action('%')).grid(row=4, column=2)
  Button(master,text="7",width=3,command=lambda:self.action('7')).grid(row=1, column=0)
  Button(master,text="8",width=3,command=lambda:self.action(8)).grid(row=1, column=1)
  Button(master,text="9",width=3,command=lambda:self.action(9)).grid(row=1, column=2)
  Button(master,text="4",width=3,command=lambda:self.action(4)).grid(row=2, column=0)
  Button(master,text="5",width=3,command=lambda:self.action(5)).grid(row=2, column=1)
  Button(master,text="6",width=3,command=lambda:self.action(6)).grid(row=2, column=2)
  Button(master,text="1",width=3,command=lambda:self.action(1)).grid(row=3, column=0)
  Button(master,text="2",width=3,command=lambda:self.action(2)).grid(row=3, column=1)
  Button(master,text="3",width=3,command=lambda:self.action(3)).grid(row=3, column=2)
  Button(master,text="0",width=3,command=lambda:self.action(0)).grid(row=4, column=0)
  Button(master,text=".",width=3,command=lambda:self.action('.')).grid(row=4, column=1)
  Button(master,text="(",width=3,command=lambda:self.action('(')).grid(row=2, column=4)
  Button(master,text=")",width=3,command=lambda:self.action(')')).grid(row=2, column=5)
  Button(master,text="√",width=3,command=lambda:self.squareroot()).grid(row=3, column=4)
  Button(master,text="x²",width=3,command=lambda:self.square()).grid(row=3, column=5)
#Main
root = Tk()
obj=calc(root) #object instantiated
root.mainloop()

Leave a Reply

Your email address will not be published.