Simple Calculator (Tkinter)

 Required libraries: 


tkinter ( pip install tkinter )



Explanation: 


modules imported:-

    1. from tkinter import * - importing every function from tkinter library

    2.messagebox - to show any popup message

calculator class:-

    1.making basic tkinter window and giving required details(background colours, geometry, etc.)

    2.frame 1 (titleFrame) :- the first frame only contains title ("gCalc") of the calculator

    3.frame 2 (workFrame) :- it have all the main stuff

        i. entryPlace : entry widget to write the equation

        ii. "=" button : button to evaluate the equation entered in the entryPlace and then print answer on it

    4. calculate function :-

        i. try and except : NameError exception is handled(if user will enter an invalid equation, it will show error in a popup window titled "typo?")

         

        ii. "eval()" function is used to evaluate any valid equation given in the entryPlace



Code : 


from tkinter import *

from tkinter import messagebox

class Calculator:

def __init__(self, master):

self.master = master

master.title("gCalc")

master.geometry("500x100")

master.configure(bg = "greenyellow", cursor = "dot")

self.titleFrame = Frame(master, borderwidth = 1, bd = 2)

self.titleLabel = Label(self.titleFrame, text = "gCalc",
                font = ("Helvetica", 22), fg = "red", bg = "greenyellow")

self.titleLabel.pack()

self.titleFrame.pack()

self.workFrame = Frame(master, bg = "greenyellow")

self.entryPlace = Entry(self.workFrame, bg = "greenyellow")

self.entryPlace.grid(row = 1, column = 2)

self.calcButton = Button(self.workFrame, text = " = ",
                bg = "cyan", command = self.calculate)

self.calcButton.grid(row = 10, column = 2)

self.workFrame.pack()
def calculate(self):

try:

problem = str(self.entryPlace.get())
ans = eval(problem)

self.entryPlace.insert(0, f" = {ans}")

except NameError:

messagebox.showerror("typo?", "invalid equation given to gCalc")

self.entryPlace.delete(0, END)


def main():

root = Tk()

gCalc = Calculator(root)

root.mainloop()

if __name__ == "__main__":

main()


@projectsofcode on instagram





Comments

Popular posts from this blog

HangMan game in PYTHON

Tic-Tac-Toe (multiplayer) using pthon

Projects to consider as a bigener in PYTHON