|
| 1 | +from kivy.app import App |
| 2 | +from kivy.uix.boxlayout import BoxLayout |
| 3 | +from kivy.uix.button import Button |
| 4 | +from kivy.uix.textinput import TextInput |
| 5 | + |
| 6 | + |
| 7 | +class CalculatorApp(App): |
| 8 | + def build(self): |
| 9 | + self.operators = ['+', '-', '*', '/'] |
| 10 | + self.last_was_operator = None |
| 11 | + self.last_button = None |
| 12 | + |
| 13 | + main_layout = BoxLayout(orientation='vertical') |
| 14 | + self.solution = TextInput( |
| 15 | + multiline=False, readonly=True, halign='right', |
| 16 | + font_size=55, size_hint=(1, 0.2) |
| 17 | + ) |
| 18 | + main_layout.add_widget(self.solution) |
| 19 | + |
| 20 | + buttons = [ |
| 21 | + ['7', '8', '9', '/'], |
| 22 | + ['4', '5', '6', '*'], |
| 23 | + ['1', '2', '3', '-'], |
| 24 | + ['.', '0', 'C', '+'], |
| 25 | + ] |
| 26 | + |
| 27 | + for row in buttons: |
| 28 | + h_layout = BoxLayout() |
| 29 | + for label in row: |
| 30 | + button = Button( |
| 31 | + text=label, |
| 32 | + pos_hint={'center_x': 0.5, 'center_y': 0.5}, |
| 33 | + font_size=32 |
| 34 | + ) |
| 35 | + button.bind(on_press=self.on_button_press) |
| 36 | + h_layout.add_widget(button) |
| 37 | + main_layout.add_widget(h_layout) |
| 38 | + |
| 39 | + equals_button = Button( |
| 40 | + text='=', pos_hint={'center_x': 0.5, 'center_y': 0.5}, |
| 41 | + font_size=32 |
| 42 | + ) |
| 43 | + equals_button.bind(on_press=self.on_solution) |
| 44 | + main_layout.add_widget(equals_button) |
| 45 | + |
| 46 | + return main_layout |
| 47 | + |
| 48 | + def on_button_press(self, instance): |
| 49 | + current = self.solution.text |
| 50 | + button_text = instance.text |
| 51 | + |
| 52 | + if button_text == 'C': |
| 53 | + self.solution.text = '' |
| 54 | + else: |
| 55 | + if current and ( |
| 56 | + self.last_was_operator and button_text in self.operators): |
| 57 | + return |
| 58 | + elif current == '' and button_text in self.operators: |
| 59 | + return |
| 60 | + else: |
| 61 | + new_text = current + button_text |
| 62 | + self.solution.text = new_text |
| 63 | + self.last_button = button_text |
| 64 | + self.last_was_operator = self.last_button in self.operators |
| 65 | + |
| 66 | + def on_solution(self, instance): |
| 67 | + text = self.solution.text |
| 68 | + if text: |
| 69 | + try: |
| 70 | + solution = str(eval(self.solution.text)) |
| 71 | + self.solution.text = solution |
| 72 | + except Exception: |
| 73 | + self.solution.text = 'Error' |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + CalculatorApp().run() |
0 commit comments