from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
class CalculatorApp(App):
def build(self):
self.icon = "calculator.png"
self.operators = ["/", "*", "+", "-"]
self.last_was_operator = None
self.last_button = None
self.solution = TextInput(background_color="black", foreground_color="white", readonly=True)
main_layout = BoxLayout(orientation="vertical")
main_layout.add_widget(self.solution)
buttons = [
["7", "8", "9", "/"],
["4", "5", "6", "*"],
["1", "2", "3", "+"],
[".", "0", "C", "-"],
]
for row in buttons:
h_layout = BoxLayout()
for label in row:
button = Button(
text=label, font_size=30, background_color="grey",
pos_hint={"center_x": 0.5, "center_y": 0.5}
)
if label == "C":
button.bind(on_press=self.clear_text)
else:
button.bind(on_press=self.button_press)
h_layout.add_widget(button)
main_layout.add_widget(h_layout)
equal_button = Button(
text="=", font_size=30, background_color="grey",
pos_hint={"center_x": 0.5, "center_y": 0.5}
)
equal_button.bind(on_press=self.calculate)
main_layout.add_widget(equal_button)
return main_layout
def button_press(self, instance):
current_text = self.solution.text
button_text = instance.text
if button_text in self.operators:
if self.last_was_operator:
return
elif current_text == "":
return
self.last_was_operator = True
self.solution.text += button_text
else:
self.last_was_operator = False
self.solution.text += button_text
def calculate(self, instance):
current_text = self.solution.text
if current_text:
try:
self.solution.text = str(eval(current_text))
except Exception:
self.solution.text = "Error"
def clear_text(self, instance):
self.solution.text = ""
if __name__ == "__main__":
app = CalculatorApp()
app.run()