Python中如何将变量值作为属性名使用,循环调用hide方法批量隐藏UI组件
错误原因
你写的self.item.hide()不会把item变量的值作为属性名查找,Python会直接尝试访问self中名为item的固定属性,和你列表中存储的属性名字符串没有关联,因此无法正常执行。
解决方案
使用Python内置的getattr()函数动态获取对象属性,该函数接收「目标对象、属性名字符串」两个核心参数,返回对应属性的引用,后续即可正常调用属性方法。
正确写法如下:
layoutList = ['BTN0','BTN1','BTN2','BTN3','BTN4','BTN5','BTN6','BTN7','BTN8','label','resetBTN'] for attr_name in layoutList: # 动态获取对应UI组件 ui_component = getattr(self, attr_name) ui_component.hide()
可选容错优化
如果担心列表中存在不存在的属性名触发AttributeError,可以给getattr()加第三个默认值参数,配合判断逻辑避免报错:
for attr_name in layoutList: ui_component = getattr(self, attr_name, None) if ui_component: ui_component.hide()
内容的提问来源于stack exchange,提问作者mohammad simorgh
相关产品推荐
相关产品推荐

