Python Calculator Using Tkinter Source Code

How To Create A Calculator In Python and Tkinter

How To Create A Calculator In Python and Tkinter


In This Python Tutorial we will See How To Make A Simple Windows Form Calculator Application To Do The Basic Operations (+, -, /, *) And Reset To Make Another  Calc Using tkinter In Visual Code Editor .





Project Source Code:

   
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *

root = Tk()

buttons = []

btns_vals = {'0-0':'1','0-1':'2','0-2':'3','0-3':'4',
'1-0':'5','1-1':'6','1-2':'7','1-3':'8',
'2-0':'9','2-1':'0','2-2':'.','2-3':'=',
'3-0':'+','3-1':'-','3-2':'/','3-3':'*',}


textbox = tk.Entry(root, width="30", font=("Arial",20))
textbox.grid(row="0", column="0", columnspan="4")


def displayVal(row_index, column_index):

# get the textbox value
textbox_val = textbox.get()
# clear textbox
textbox.delete(0,END)
# get the clicked button value
btn_val = buttons[row_index][column_index]['text']
# new val
val = textbox_val + btn_val
# display the new val in textbox
textbox.insert(0,val)


# create a function to calculate
def calc(opr):
if opr != '=':
global calc_opr, number_1
calc_opr = opr
number_1 = float(textbox.get())
textbox.delete(0,END)

elif opr == '=':
number_2 = float(textbox.get())
if calc_opr == '+':
val = number_1 + number_2
elif calc_opr == '-':
val = number_1 - number_2
elif calc_opr == '/':
val = number_1 / number_2
elif calc_opr == '*':
val = number_1 * number_2

textbox.delete(0,END)
textbox.insert(0,val)



# create a function to clear textbox
def clear():
textbox.delete(0,END)


# display buttons
for i in range(4):
btn_row = []
for j in range(4):
key = "{i}-{j}".format(i=i,j=j)
button = tk.Button(root, padx=15, pady=15, text = btns_vals[key],
font=("Arial",20))

if btns_vals[key] not in ('=','+','-','*','/'):
button['bg'] = 'Black'
button['fg'] = 'White'
button['command'] = lambda theRow = i,
theCol = j : displayVal(theRow, theCol)

else:
button['bg'] = 'Orange'
button['fg'] = 'White'
button['command'] = lambda operation = btns_vals[key] : calc(operation)


button.grid(row=i+1, column=j, sticky="nsew")

btn_row.append(button)

buttons.append(btn_row)


button = tk.Button(root, padx=15, pady=15,bg="grey", text = 'c', font=("Arial",20))
button['command'] = clear
button.grid(row=5,column=0,columnspan=4, sticky="nsew")

root.mainloop()



                                        



////// OUTPUT : 

Calculator In Python and Tkinter




if you want the source code file, click on the download button below

download the source code













Share this

Related Posts

Previous
Next Post »