How To Create Mini Calculator In Python

Python have a capability to makes code optimize and make everything easy to create so we can create a mini calculator in python very easily and in just 13 to 14 line code. We use IDLE (python 3.5) to create this project.

Lets go,

Now, we start creating our calculator step by step.

Step 1: Open IDLE (python 3.5). After launching IDLE(python 3.5) a window is visible as in the following screenshot:

Open a new file for write our source code (shown in picture),

New file is open and ready to write our code....(shown in picture),

Step 2: write our source code

Firstly, we have to do import all module (namespace) used in this project,
  1. from tkinter import * # this module contains graphic function  
  2. from math import * #this module contains mathematics function  
We shall move further, now we define a function that execute our expression and read value from text box.
  1. def calculate(event):  
  2. l.configure(text = "Result: " + str(eval(e.get())))  
Here we define a function named "calculate" and used pre define function str() ,eval() andget(),
  • str() is used to type casting.
  • eval() is used to execute our expression and return result.
  • get() return text from Entry(text box) in string format
l is instance of label configure() is use to configuration label. After defining a function, we have to create a windows form,
  1. w = Tk() # create instance  
  2. w.geometry("300x300") # set size of form  
  3. w.title("calculator") #set title  
Window form is created and add some controls and call our function "calculate",
  1. Label(w, text="Enter Your Expression:").pack() #define label and bind with form  
  2. e = Entry(w) # define text box  
  3. e.bind("<Return>", calculate) #calling calculate  
  4. e.pack() #bind text box with window form  
  5. l = Label(w) #here define label to shoe our result  
  6. l.pack()  
  7. w.mainloop()  
Now our source code is:
  1. from tkinter import *  
  2. from math import *  
  3. def calculate(event):  
  4. l.configure(text = "Result: " + str(eval(e.get())))  
  5. w = Tk()  
  6. w.geometry("300x300")  
  7. w.title("calculator")  
  8. Label(w, text="Enter Your Expression:").pack()  
  9. e = Entry(w)  
  10. e.bind("<Return>", calculate)  
  11. e.pack()  
  12. l = Label(w)  
  13. l.pack()  
  14. w.mainloop()  
Run our project (press F5) and output looks like. (shown in picture).

Enter expression: 2+3