获取ID时出现异常:__super__对象无__getattr__属性求助
问题描述
需要检查64个按钮中是否存在带有指定ID的AsyncImage(仅16个按钮包含图片),编写相关函数后运行脚本出现错误:__super__ object has no attribute '__getattr__'。
.kv代码示例
Button: id: button_1 background_normal: '' background_color: (1,1,1,1) on_press: root.moves(self, root) AsyncImage: id: white_1 source: 'imgs/WhiteCastle.png' center_x: self.parent.center_x center_y: self.parent.center_y Button: id: button_2 background_color: (0, 0, 0, 1) on_press: root.moves(self, root) AsyncImage: id: white_2 source: 'imgs/WhiteKnight.png' center_x: self.parent.center_x center_y: self.parent.center_y Button: id: button_3 background_normal: '' background_color: (1,1,1,1) on_press: root.moves(self, root) AsyncImage: id: white_3 source: 'imgs/WhiteBishop.png' center_x: self.parent.center_x center_y: self.parent.center_y
原始.py代码
def img_list(self): img_ids_list = [] for x in range(1, 17): img_ids_list.append(f"white_{x}") for y in range(1, 17): img_ids_list.append(f"black_{y}") return img_ids_list def moves(self, instance, root): all_ids = root.ids id_of_button = self.get_id(instance) img_id = self.check_if_img_exists(instance, root) def check_if_img_exists(self, instance, root): img_ids = self.img_list() if img_ids[0] in root.ids: print("Ready for launch!") for x in range(1, 32): imag = img_ids[x] asyncImage = root.ids.imag if asyncImage in instance.children: print("Button contains an AsyncImage") return asyncImage print("Button does not contain an AsyncImage") def get_id(self, instance): for id, widget in instance.parent.parent.ids.items(): if widget.__self__ == instance: return id
错误原因及修复方案
核心错误点
错误__super__ object has no attribute '__getattr__'由root.ids.imag引发:这里试图直接访问root.ids的imag属性,但imag是变量名,正确的方式应该是通过字典索引root.ids[imag]来获取对应ID的控件。
其他问题及修复
- 函数缩进错误:
img_list函数内的循环和return语句未缩进,导致变量img_ids_list未在函数作用域内定义,修复后将代码块缩进至函数内。 - 循环范围错误:
check_if_img_exists中循环从range(1,32)开始,会跳过第一个图片ID(索引0),且未覆盖全部32个ID(16白+16黑),改为动态遍历更灵活。 - 控件实例对比错误:
get_id中使用widget.__self__ == instance是错误的,直接对比widget == instance即可,因为ids中存储的就是控件实例本身。 - 低效的检查逻辑:不需要通过全局
root.ids查找后再判断是否在按钮子控件中,直接遍历按钮的children并检查其id是否在目标列表中更高效。
修复后的.py代码
def img_list(self): img_ids_list = [] # 缩进修复:循环放在函数内部 for x in range(1, 17): img_ids_list.append(f"white_{x}") for y in range(1, 17): img_ids_list.append(f"black_{y}") return img_ids_list def moves(self, instance, root): all_ids = root.ids id_of_button = self.get_id(instance) img_widget = self.check_if_img_exists(instance, root) # 可在此添加对img_widget的后续处理 def check_if_img_exists(self, instance, root): target_img_ids = self.img_list() # 直接遍历按钮子控件,高效匹配目标ID for child in instance.children: if hasattr(child, 'id') and child.id in target_img_ids: print("Button contains an AsyncImage") return child print("Button does not contain an AsyncImage") return None def get_id(self, instance): # 修复实例对比逻辑 for id, widget in instance.parent.parent.ids.items(): if widget == instance: return id return None # 添加默认返回值,避免无匹配时出错
内容的提问来源于stack exchange,提问作者le coder
相关产品推荐
相关产品推荐

