Complete Tkinter Calculator - uber1337 - 03-06-2010
I completed my calculator script, it now has features such as memory and +/-, it also has basic error handling. If you want to make one on your own, look at this and/or this. It handles string and int concatenation and zero division errors, and is 100% error proof(from my knowledge). Anyway, here is the source:
Code: from Tkinter import *
mem = ''
class calc(Frame):
def __init__(self):
global result
top = Tk()
top.title('UberCalc v2.5')
Frame.__init__(self)
result = Entry()
result.pack(side=TOP)
buttons = ['M+', 'M', '+/-', '1', '2', '3','4', '5', '6','7', '8', '9','.', '0', 'Clear']
operbtn = ['-','+', '*','/', '=']
ro = 1
col = 0
for x in buttons:
action = lambda y=x: onclick(y)
Button(self, text=x, width=5, relief='ridge', command=action).grid(row=ro, column=col)
col += 1
if col > 2:
col = 0
ro += 1
col = 4
ro = 1
for x in operbtn:
action = lambda y=x:onclick(y)
Button(self, text=x, width=5, relief='ridge', command=action).grid(row=ro, column=col)
ro += 1
def onclick(key):
global result, mem
if key == '=':
try:
fetch = result.get()
answer = eval(fetch)
result.delete(0, END)
result.insert(0, answer)
except(ZeroDivisionError):
result.delete(0, END)
result.insert(0, 'Do not divide by zero please')
except(SyntaxError):
result.delete(0, END)
result.insert(0, '0')
elif key == 'Clear':
result.delete(0, END)
elif key == 'M+':
mem = result.get()
result.delete(0, END)
elif key == 'M':
result.insert(END, mem)
elif key == '+/-':
if result.get()[0] == '-':
result.delete(0)
else:
result.insert(0, '-')
else:
result.insert(END, key)
if __name__ == '__main__':
window = calc()
window.pack()
window.mainloop()
If you have any questions about how this works, feel free to ask on this thread. PM me or add me on MSN (ub3rl33t@msn.com) for any python questions.
|