-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.py
91 lines (64 loc) · 2.7 KB
/
calc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from tkinter import Tk, Entry, StringVar, Button
class Expression:
expression = ""
@classmethod
def set(cls, expression):
cls.expression = expression
return cls.expression
@classmethod
def get(cls):
return cls.expression
def on_button_press(equation, value):
Expression.set(Expression.get() + str(value))
equation.set(Expression.get())
def on_equal_button_press(equation):
try:
total = str(eval(Expression.get()))
equation.set(total)
except:
equation.set(" error ")
finally:
Expression.set("")
def on_clear_button_press(equation):
Expression.set("")
equation.set("")
def create_window(tkinter):
tkinter.configure(background="Black")
tkinter.title("Basic Calculator")
tkinter.geometry("280x200")
return tkinter
def add_buttons(tkinter, equation):
add_button(tkinter, ' 1 ', lambda: on_button_press(equation, '1'), 2, 0)
add_button(tkinter, ' 2 ', lambda: on_button_press(equation, '2'), 2, 1)
add_button(tkinter, ' 3 ', lambda: on_button_press(equation, '3'), 2, 2)
add_button(tkinter, ' 4 ', lambda: on_button_press(equation, '4'), 3, 0)
add_button(tkinter, ' 5 ', lambda: on_button_press(equation, '5'), 3, 1)
add_button(tkinter, ' 6 ', lambda: on_button_press(equation, '6'), 3, 2)
add_button(tkinter, ' 7 ', lambda: on_button_press(equation, '7'), 4, 0)
add_button(tkinter, ' 8 ', lambda: on_button_press(equation, '8'), 4, 1)
add_button(tkinter, ' 9 ', lambda: on_button_press(equation, '9'), 4, 2)
add_button(tkinter, ' 0 ', lambda: on_button_press(equation, '0'), 5, 0)
add_button(tkinter, ' + ', lambda: on_button_press(equation, '+'), 6, 0)
add_button(tkinter, ' - ', lambda: on_button_press(equation, '-'), 6, 1)
add_button(tkinter, ' * ', lambda: on_button_press(equation, '*'), 6, 2)
add_button(tkinter, ' / ', lambda: on_button_press(equation, '/'), 7, 0)
add_button(tkinter, ' = ', lambda: on_equal_button_press(equation), 5, 2)
add_button(tkinter, ' Clear ', lambda: on_clear_button_press(equation), 5, 1)
def add_button(tkinter, text, command, row, column):
button = Button(tkinter,text=text,fg='white',bg='black',command=command,height=1,width=7)
button.grid(row=row, column=column)
def add_textbox(tkinter):
equation = StringVar()
expression_field = Entry(tkinter, textvariable=equation)
expression_field.grid(columnspan=4, pady=(0, 3), ipadx=65)
return equation
def render_window(tkinter):
tkinter.mainloop()
def run():
tkinter = Tk()
tkinter = create_window(tkinter)
equation = add_textbox(tkinter)
add_buttons(tkinter, equation)
render_window(tkinter)
if __name__ == "__main__":
run()