from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
class Calculadora(App):
def build(self):
return InterfazCalculadora()
class InterfazCalculadora(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.orientation = 'vertical'
self.display = Label(text='0', font_size=40, halign='right', valign='middle', size_hint=(1, 0.3))
self.add_widget(self.display)
self.buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'.', '0', '=', '+'
]
grid = BoxLayout(orientation='horizontal', size_hint=(1, 0.7), row_force_default=True, row_default_height=40)
for button_text in self.buttons:
btn = Button(text=button_text, font_size=30)
btn.bind(on_press=self.on_button_click)
grid.add_widget(btn)
self.add_widget(grid)
self.current_operation = ''
def on_button_click(self, instance):
text = instance.text
if text == '=':
try:
self.display.text = str(eval(self.current_operation))
self.current_operation = ''
except Exception:
self.display.text = 'Error'
self.current_operation = ''
elif text == 'C':
self.display.text = '0'
self.current_operation = ''
else:
self.current_operation += text
self.display.text = self.current_operation
if __name__ == '__main__':
Calculadora().run()