Mini Project | Python+Tkinter | GUI Calculator (Complete Working Code for Students)
from tkinter import *
import tkinter.messagebox
#==========================Settings====================
root = Tk()
root.geometry('400x160')
root.title('Calculator')
color='gray60'
root.configure(bg=color)
root.resizable(width=False, height=False)
#==========================Variables===================
num1=StringVar()
num2=StringVar()
res_value=StringVar()
#==========================Frames======================
top_first=Frame(root,width=400,height=40,bg=color)
top_first.pack(side=TOP)
top_second=Frame(root,width=400,height=40,bg=color)
top_second.pack(side=TOP)
top_third=Frame(root,width=400,height=40,bg=color)
top_third.pack(side=TOP)
top_forth=Frame(root,width=400,height=40,bg=color)
top_forth.pack(side=TOP)
#==========================Functions===================
def errorMsg(ms):
if ms=='error':
tkinter.messagebox.showerror('Error!','Something went wrong')
elif ms=='divisionerror':
tkinter.messagebox.showerror('Error!',"Can't divide by 0")
def plus():
try:
value=float(num1.get())+float(num2.get())
res_value.set(value)
except:
errorMsg('error')
def minus():
try:
value=float(num1.get())-float(num2.get())
res_value.set(value)
except:
errorMsg('error')
def mul():
try:
value=float(num1.get())*float(num2.get())
res_value.set(value)
except:
errorMsg('error')
def div():
if num2.get()=='0':
errorMsg('divisionerror')
else:
try:
value=float(num1.get())/float(num2.get())
res_value.set(value)
except:
errorMsg('error')
#==========================Buttons=====================
btn_plus=Button(top_third,text='+',width=6,
highlightbackground=color,command=lambda : plus())
btn_plus.pack(side=LEFT,padx=5,pady=5)
btn_minus=Button(top_third,text='-',width=6,
highlightbackground=color,command=lambda : minus())
btn_minus.pack(side=LEFT,padx=5,pady=5)
btn_mul=Button(top_third,text='*',width=6,
highlightbackground=color,command=lambda : mul())
btn_mul.pack(side=LEFT,padx=5,pady=5)
btn_div=Button(top_third,text='/',width=6,
highlightbackground=color,command=lambda : div())
btn_div.pack(side=LEFT,padx=5,pady=5)
#==========================Labels+Entries==============
label_first=Label(top_first,text="Enter number-1: ",bg=color)
label_first.pack(side=LEFT,padx=5,pady=5)
first_num=Entry(top_first,highlightbackground=color,textvariable=num1)
first_num.pack(side=LEFT)
label_second=Label(top_second,text="Enter number-2: ",bg=color)
label_second.pack(side=LEFT,padx=5,pady=5)
second_num=Entry(top_second,highlightbackground=color,textvariable=num2)
second_num.pack(side=LEFT)
res=Label(top_forth,text="Result: ",bg=color)
res.pack(side=LEFT,padx=5,pady=5)
res1=Entry(top_forth,highlightbackground=color,textvariable=res_value)
res1.pack(side=LEFT)
root.mainloop()
This Project helped me a lot in developing calculator application
ReplyDelete