以下是一个简单的加减法计算器的Kivy代码:
```
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
class CalculatorApp(App):
def build(self):
self.equation = ""
layout = BoxLayout(orientation='vertical')
self.label = Label(text="0", font_size=50, size_hint=(1, 0.5))
layout.add_widget(self.label)
button_layout = BoxLayout()
buttons = [
["7", "8", "9", "+"],
["4", "5", "6", "-"],
["1", "2", "3", "="],
["C", "0", ".", ""]
]
for row in buttons:
row_layout = BoxLayout()
for label in row:
button = Button(text=label, font_size=30, size_hint=(0.25, 0.25))
button.bind(on_press=self.button_pressed)
row_layout.add_widget(button)
button_layout.add_widget(row_layout)
layout.add_widget(button_layout)
return layout
def button_pressed(self, instance):
label = instance.text
if label == "C":
self.equation = ""
self.label.text = "0"
elif label == "=":
try:
result = str(eval(self.equation))
self.label.text = result
self.equation = result
except:
self.label.text = "Error"
self.equation = ""
else:
self.equation += label
self.label.text = self.equation
if __name__ == '__main__':
CalculatorApp().run()
```
这个计算器使用BoxLayout布局,包含一个Label和一个按钮布局。按钮布局包含四个行,每行包含四个按钮。当用户按下按钮时,它们的标签将添加到equation字符串中,并显示在Label上。如果用户按下“C”按钮,则清除equation字符串和Label。如果用户按下“=”按钮,则计算equation字符串的结果并显示在Label上。如果计算失败,则显示“Error”。