在这个小程序中添加一个退出按钮,点击退出,就可以退出程序

动态 未结 0 90
小小草
小小草 LV1 2023年9月23日 23:40 发表
可以在按钮布局中添加一个“退出”按钮,然后为它绑定一个回调函数来退出应用程序。以下是修改后的代码: ``` 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()来停止应用程序。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复