-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.py
46 lines (35 loc) · 1.23 KB
/
calculator.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
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
BUTTONS_NAMES = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['.', '0', '=', '+'],
]
class CalculatorApp(App):
def build(self):
self.expression = ""
grid = BoxLayout(orientation='vertical')
self._display = Label(text='0', font_size=24, size_hint=(1, 0.75))
grid.add_widget(self._display)
for button_names_row in BUTTONS_NAMES:
grid_row = BoxLayout()
for button_name in button_names_row:
button = Button(text=button_name, font_size=24, on_press=self.on_button_press)
grid_row.add_widget(button)
grid.add_widget(grid_row)
return grid
def on_button_press(self, button):
if button.text == '=':
try:
self._display.text = str(eval(self.expression))
except SyntaxError:
self._display.text = 'Error'
self.expression = ""
else:
self.expression += button.text
self._display.text = self.expression
if __name__ == '__main__':
CalculatorApp().run()