可以在按钮布局中添加一个“退出”按钮,然后为它绑定一个回调函数来退出应用程序。以下是修改后的代码:
```
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", ".", "Quit"]
]
for row in buttons:
row_layout = BoxLayout()
for label in row:
button = Button(text=label, font_size=30, size_hint=(0.25, 0.25))
if label == "Quit":
button.bind(on_press=self.quit_app)
else:
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
def quit_app(self, instance):
App.get_running_app().stop()
if __name__ == '__main__':
CalculatorApp().run()
```
在按钮布局中添加了一个“Quit”按钮,并为它绑定了一个名为quit_app的回调函数。当用户按下该按钮时,该函数将调用App.get_running_app().stop()来停止应用程序。