
本文详解Kivy中因ID命名大小写不匹配导致的AttributeError: 'super' object has no attribute '__getattr__'错误,并提供正确访问控件ID的规范做法。
本文详解kivy中因id命名大小写不匹配导致的`attributeerror: 'super' object has no attribute '__getattr__'`错误,并提供正确访问控件id的规范做法。
在Kivy开发中,通过self.ids.
✅ 正确写法:确保ID名称完全一致
修改Python端访问语句,使ID名称与KV文件中定义的完全一致(包括下划线位置和大小写):
# ✅ 正确:KV中定义的是 id: name_label → Python中必须用 name_label self.ids.name_label.text = "Is your name " + name + " ?"
⚠️ 其他关键注意事项
- ids仅在组件完成KV绑定后可用:确保在on_enter、on_pre_enter或绑定的回调(如按钮on_press)中访问self.ids,避免在__init__或build()中过早调用;
- ID必须在当前作用域内定义:self.ids仅包含当前Widget(此处为InputScreen)及其子树中声明的ID,不能跨Screen或跨层级访问;
-
推荐添加存在性校验(健壮性增强):
if hasattr(self, 'ids') and 'name_label' in self.ids: self.ids.name_label.text = f"Is your name {name} ?" else: print("Warning: name_label ID not found in current screen.")
? 完整可运行修正版代码
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
sm = ScreenManager() # 注意:需提前定义,否则build()中add_widget会报错
class MyApp(App):
def build(self):
sm.add_widget(InputScreen(name="Input"))
return sm
Builder.load_string('''
<inputscreen>:
BoxLayout:
orientation: 'vertical'
Label:
id: name_label
text: "x"
Button:
text: "Ask Name"
on_press: root.press()
''')
class InputScreen(Screen):
def press(self):
name = "Trevor"
# ✅ 修正大小写:name_label(非name_Label)
self.ids.name_label.text = "Is your name " + name + " ?"
if __name__ == '__main__':
MyApp().run()</inputscreen>
? 小结:Kivy的ids机制本质是字典映射,而非动态属性代理。所有ID访问都依赖精确的字符串匹配。养成“KV定义什么,Python就写什么”的习惯,并善用IDE的语法高亮与自动补全,可大幅减少此类低级错误。











