KivyMD报错AttributeError: 'Programa' object has no attribute 'root'如何解决
问题修复方案
错误原因
报错由三个问题共同导致:
Programa类本身就是KV文件中定义的根布局,root是MDApp实例的属性,你在Programa的实例方法中调用self.root自然会报属性不存在的错误,直接通过self.ids即可访问KV中定义的控件。- KV文件里第一个输入框的id是
soma,你代码中写的是namee,id不匹配也会导致找不到控件。 TesteApp的build方法没有返回根布局实例,运行时无法正常加载你写的KV界面。
修复代码
修改后的main.py
from kivymd.app import MDApp from kivymd.uix.boxlayout import MDBoxLayout class Programa(MDBoxLayout): def calcular(self): # 直接通过self.ids访问对应id的输入框 print("O valor de soma é {}".format(self.ids.soma.text)) # 如果你需要获取另外两个输入框的值,给它们加上id后用同样方式调用即可 # print(self.ids.digitos.text) # print(self.ids.excecao.text) class TesteApp(MDApp): def build(self): # 返回根布局实例,加载KV界面 return Programa() # 补充工具栏调用的callback方法,避免点击菜单按钮时报错 def callback(self): pass TesteApp().run()
可选优化KV文件(给另外两个输入框加id方便后续取值)
Programa: MDGridLayout: cols: 1 MDToolbar: title: "SDK Calc" left_action_items: [["menu", lambda x: app.callback()]] MDGridLayout: cols: 1 padding: [22,32] MDTextField: id: soma hint_text: "Soma" MDTextField: id: digitos hint_text: "Digitos" MDTextField: id: excecao hint_text: "Exceção" MDFillRoundFlatIconButton: text: "Calcular" icon: "calculator-variant-outline" on_release: root.calcular() pos_hint: {"center_x": .5, "center_y": .5}
内容的提问来源于stack exchange,提问作者WCout
相关产品推荐
相关产品推荐

