-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtkinter_calculator.py
More file actions
74 lines (58 loc) · 1.97 KB
/
Copy pathtkinter_calculator.py
File metadata and controls
74 lines (58 loc) · 1.97 KB
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
from tkinter import *
import ast
root = Tk()
i = 0
def get_number(num):
global i
display.insert(i, num)
i+=1
def get_operation(operator):
global i
length = len(operator)
display.insert(i, operator)
i += length
def clear_all():
display.delete(0, END)
def calculate():
entire_string = display.get()
try:
node = ast.parse(entire_string, mode = "eval")
result = eval(compile(node, '<string>', 'eval'))
clear_all()
display.insert(0, result)
except Exception:
clear_all()
display.insert(0, "Error")
def undo():
entire_string = display.get()
if len(entire_string):
new_string = entire_string[:-1]
clear_all()
display.insert(0,new_string)
else:
clear_all()
display.insert(0,"")
display = Entry(root)
display.grid(row = 1, columnspan = 6)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
counter = 0
for x in range(3):
for y in range(3):
button_text = numbers[counter]
button = Button(root, text = button_text, width = 2, height = 2, command = lambda text = button_text: get_number(text))
button.grid(row = x + 2 , column = y)
counter += 1
button = Button(root, text = "0", width = 2, height = 2, command = lambda : get_number(0))
button.grid(row = 5, column = 1)
operations = ['+', '-', '*', '/', '*3.14', '%', '(', '**', ')', '**2']
count = 0
for x in range(4):
for y in range(3):
if count<len(operations):
button = Button(root, text = operations[count], width = 2, height = 2, command = lambda operator = operations[count]: get_operation(operator))
count +=1
button.grid(row = x+2, column = y+3)
Button(root, text = "AC", width = 2, height = 2, command = clear_all).grid(row = 5, column = 0)
Button(root, text = "=", width = 2, height = 2, command = calculate).grid(row = 5, column = 2)
Button(root, text="<-", width=2, height=2, command=lambda: undo()).grid(row=5, column=4)
root.mainloop()