|
| 1 | +from tkinter import* |
| 2 | + |
| 3 | +def fCalc(src, side): |
| 4 | + appObj = Frame(src, borderwidth=4, bd=2,bg = "#000000") |
| 5 | + appObj.pack(side=side, expand=YES, fill=BOTH) |
| 6 | + return appObj |
| 7 | + |
| 8 | +def button(src, side, text, command=None): |
| 9 | + appObj = Button(src, text=text, command=command) |
| 10 | + appObj.pack(side=side, expand=YES, fill=BOTH) |
| 11 | + return appObj |
| 12 | + |
| 13 | +class app(Frame): |
| 14 | + def __init__(self, root = Tk(), width=364, height=425): |
| 15 | + Frame.__init__(self) |
| 16 | + self.option_add("*Font", 'arial 20 bold') |
| 17 | + self.pack(expand=YES, fill=BOTH) |
| 18 | + self.master.title("Python calculator") |
| 19 | + screen_width = root.winfo_screenwidth() |
| 20 | + screen_height = root.winfo_screenheight() |
| 21 | + x = (screen_width/2) - (width/2) |
| 22 | + y = (screen_height/2) - (height/2) |
| 23 | + root.geometry('%dx%d+%d+%d' % (width, height, x, y)) |
| 24 | + display = StringVar() |
| 25 | + Entry(self, relief= RIDGE, |
| 26 | + textvariable=display, state=DISABLED, justify='right', bd=20, bg = "#000000").pack(side=TOP, expand=YES, |
| 27 | + fill=BOTH) |
| 28 | + clrChar = "Clear" |
| 29 | + button(self, TOP, clrChar, lambda appObj=display, i=clrChar: appObj.set('')) |
| 30 | + |
| 31 | + |
| 32 | + for btnNum in ("789/", "456*", "123-", "0.+"): |
| 33 | + |
| 34 | + FunctionNum = fCalc(self, TOP) |
| 35 | + for fEquals in btnNum: |
| 36 | + button(FunctionNum, LEFT, fEquals, |
| 37 | + lambda appObj=display, i=fEquals: appObj.set(appObj.get() + i)) |
| 38 | + EqualsButton = fCalc(self, TOP) |
| 39 | + |
| 40 | + for fEquals in "=": |
| 41 | + if fEquals == "=": |
| 42 | + btnEquals = button(EqualsButton, LEFT, fEquals) |
| 43 | + btnEquals.bind('<ButtonRelease-1>', |
| 44 | + lambda e, s=self, appObj=display: s.result(appObj), "+") |
| 45 | + else: |
| 46 | + btnEquals = button(EqualsButton, LEFT, fEquals, |
| 47 | + lambda appObj=display, s=" %s "%fEquals: appObj.set(appObj.get()+s)) |
| 48 | + |
| 49 | + def result(self, display): |
| 50 | + try: |
| 51 | + display.set(eval(display.get())) |
| 52 | + except: |
| 53 | + display.set("Error") |
| 54 | + |
| 55 | +if __name__ == '__main__': |
| 56 | + app().mainloop() |
| 57 | + |
| 58 | + |
0 commit comments