Kivy中点击组件后如何获取并判断其ID属性
解决Kivy中访问Label组件ID进行判断的问题
错误原因
你代码里的self.ids是当前Clickable_Label实例的子组件ID字典,而你的Label没有子组件,所以它是空字典,自然无法和字符串'sample_label'比较。Label自身的ID是存储在它的父容器(GridLayout)的ids字典里,所以直接在Label类内部用self.ids拿不到自己的ID。
解决方法
下面提供两种简单可行的方案:
方案一:给Label添加自定义属性存储ID
在kv语言中给每个Clickable_Label定义一个自定义属性(比如my_id),把ID值赋值给这个属性,之后在Python代码里直接访问该属性进行判断。
修改后的完整代码:
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.label import Label from kivy.lang import Builder Builder.load_string(""" <MyGridLayout> GridLayout: cols: 2 size: root.width, root.height Clickable_Label: id: sample_label_1 my_id: "sample_label_1" # 添加自定义属性存储ID text: "sample text 1" font_size: 18 Clickable_Label: id: sample_label_2 my_id: "sample_label_2" # 添加自定义属性存储ID text: "sample text 2" font_size: 18 """) class MyGridLayout(Widget): pass class Clickable_Label(Label): def on_touch_down(self, touch): if self.collide_point(*touch.pos): # 访问自定义属性my_id进行判断 if self.my_id == 'sample_label_1': print(f"{self.text} is clicked") elif self.my_id == 'sample_label_2': print(f"{self.text} is clicked") class MyApp(App): def build(self): return MyGridLayout() if __name__ == '__main__': MyApp().run()
方案二:通过父组件的ids反向查找ID
如果不想添加自定义属性,可以通过Label的父组件(GridLayout)的ids字典,遍历键值对找到当前实例对应的ID字符串:
修改后的Clickable_Label类代码:
class Clickable_Label(Label): def on_touch_down(self, touch): if self.collide_point(*touch.pos): # 遍历父组件的ids,找到当前实例对应的ID for id_str, widget in self.parent.ids.items(): if widget is self: if id_str == 'sample_label_1' or id_str == 'sample_label_2': print(f"{self.text} is clicked (ID: {id_str})") break
说明
方案一更简洁高效,推荐使用;方案二适合不想修改kv代码的场景,但需要注意父组件的层级,如果Label嵌套更深,需要调整self.parent为对应的容器组件。
内容的提问来源于stack exchange,提问作者BlueHawk77
相关产品推荐
相关产品推荐

