-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_app.py
60 lines (44 loc) · 1.87 KB
/
simple_app.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
from Tkinter import Tk, Label, Button, Entry, IntVar, END, W, E
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
self.total = 0
self.entered_number = 0
self.total_label_text = IntVar()
self.total_label_text.set(self.total)
self.total_label = Label(master, textvariable=self.total_label_text)
self.label = Label(master, text="Total:")
vcmd = master.register(self.validate) # we have to wrap the command
self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
self.add_button = Button(master, text="+", command=lambda: self.update("add"))
self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))
# LAYOUT
self.label.grid(row=0, column=0, sticky=W)
self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
self.entry.grid(row=1, column=0, columnspan=3, sticky=W+E)
self.add_button.grid(row=2, column=0)
self.subtract_button.grid(row=2, column=1)
self.reset_button.grid(row=2, column=2, sticky=W+E)
def validate(self, new_text):
if not new_text: # the field is being cleared
self.entered_number = 0
return True
try:
self.entered_number = int(new_text)
return True
except ValueError:
return False
def update(self, method):
if method == "add":
self.total += self.entered_number
elif method == "subtract":
self.total -= self.entered_number
else: # reset
self.total = 0
self.total_label_text.set(self.total)
self.entry.delete(0, END)
root = Tk()
my_gui = Calculator(root)
root.mainloop()