| 6 | |
| 7 | |
| 8 | class myApp(App): |
| 9 | def build(self): |
| 10 | root_widget = BoxLayout(orientation="vertical") |
| 11 | output_label = Label(size_hint_y=0.75, font_size=50) |
| 12 | button_symbols = ( |
| 13 | "1", |
| 14 | "2", |
| 15 | "3", |
| 16 | "+", |
| 17 | "4", |
| 18 | "5", |
| 19 | "6", |
| 20 | "-", |
| 21 | "7", |
| 22 | "8", |
| 23 | "9", |
| 24 | ".", |
| 25 | "0", |
| 26 | "*", |
| 27 | "/", |
| 28 | "=", |
| 29 | ) |
| 30 | button_grid = GridLayout(cols=4, size_hint_y=2) |
| 31 | for symbol in button_symbols: |
| 32 | button_grid.add_widget(Button(text=symbol)) |
| 33 | |
| 34 | clear_button = Button(text="Clear", size_hint_y=None, height=100) |
| 35 | |
| 36 | def print_button_text(instance): |
| 37 | output_label.text += instance.text |
| 38 | |
| 39 | for button in button_grid.children[1:]: |
| 40 | button.bind(on_press=print_button_text) |
| 41 | |
| 42 | def resize_label_text(label, new_height): |
| 43 | label.fontsize = 0.5 * label.height |
| 44 | |
| 45 | output_label.bind(height=resize_label_text) |
| 46 | |
| 47 | def evaluate_result(instance): |
| 48 | try: |
| 49 | output_label.text = str(eval(output_label.text)) |
| 50 | except SyntaxError: |
| 51 | output_label.text = "Python Syntax error!" |
| 52 | |
| 53 | button_grid.children[0].bind(on_press=evaluate_result) |
| 54 | |
| 55 | def clear_label(instance): |
| 56 | output_label.text = " " |
| 57 | |
| 58 | clear_button.bind(on_press=clear_label) |
| 59 | |
| 60 | root_widget.add_widget(output_label) |
| 61 | root_widget.add_widget(button_grid) |
| 62 | root_widget.add_widget(clear_button) |
| 63 | return root_widget |
| 64 | |
| 65 | |