Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/python-kivy-calc-1/main.py
5925 views
1
from kivy.app import App
2
from kivy.uix.button import Button
3
from kivy.uix.boxlayout import BoxLayout
4
from kivy.uix.textinput import TextInput
5
6
7
class MainApp(App):
8
def build(self):
9
main_layout = BoxLayout(orientation="vertical", padding=10, spacing=10)
10
self.solution = TextInput(multiline=False, readonly=False, halign="right", font_size=55)
11
main_layout.add_widget(self.solution)
12
buttons = [
13
["7", "8", "9", "/"],
14
["4", "5", "6", "*"],
15
["1", "2", "3", "-"],
16
[".", "0", "C", "+"],
17
]
18
for row in buttons:
19
h_layout = BoxLayout()
20
for label in row:
21
button = Button(text=label, pos_hint={"center_x": 0.5, "center_y": 0.5})
22
button.bind(on_press=self.on_button_press)
23
h_layout.add_widget(button)
24
main_layout.add_widget(h_layout)
25
26
equals_button = Button(text="=", pos_hint={"center_x": 0.5, "center_y": 0.5})
27
equals_button.bind(on_press=self.on_solution)
28
main_layout.add_widget(equals_button)
29
30
# return a Button() as a root widget
31
return main_layout
32
33
def on_button_press(self, instance):
34
if instance.text == "C":
35
self.solution.text = ""
36
else:
37
self.solution.text += instance.text
38
39
def on_solution(self, instance):
40
if self.solution.text:
41
try:
42
self.solution.text = str(eval(self.solution.text))
43
except:
44
self.solution.text = "Error"
45
46
47
if __name__ == '__main__':
48
MainApp().run()
49
50