-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcalc2.py
More file actions
74 lines (69 loc) · 1.79 KB
/
calc2.py
File metadata and controls
74 lines (69 loc) · 1.79 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
"""
### Calculator Sample
This sample demonstrates how to create a simple calculator using TkEasyGUI.
It also shows how to create multiple buttons and handle button events effectively.
"""
import TkEasyGUI as eg
eg.set_theme("alt")
# define the calculator buttons
calc_buttons = [
["C", "←", "//", "/"],
["7", "8", "9", "*"],
["4", "5", "6", "-"],
["1", "2", "3", "+"],
["0", ".", "%", "="],
]
font = ("Helvetica", 20)
# create window
layout = [
[
eg.Input(
"0",
key="-output-",
background_color="white",
color="black",
readonly_background_color="white",
readonly=True,
expand_x=True,
)
],
]
# create many buttons
for row in calc_buttons:
buttons = []
for ch in row:
btn = eg.Button(
ch, # label
key=f"-btn{ch}",
size=(5, 3),
)
buttons.append(btn)
layout.append(buttons)
window = eg.Window("Calc", layout, font=font)
# event loop
output = "0"
for event, values in window.event_iter():
if event == eg.WINDOW_CLOSED:
break
# when a button is pressed
if event.startswith("-btn"):
# get label
ch = window[event].get()
# clear if text is empty (0 or error)
if output == "0" or output.startswith("E:"):
output = ""
# check label
if ch == "C": # clear key
output = "0"
elif ch == "←": # bs key
output = output[:-1]
elif ch == "=": # calc
try:
output = str(eval(output))
except Exception as e:
output = "E:" + str(e)
else:
# add other key
output += ch
# update display
window["-output-"].update(output)