You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy/KivyMD开发中如何获取被点击的子Button控件索引

KivyMD中获取被点击Button索引值的实现方案

核心思路

不要依赖按钮的text、name属性匹配索引,也不要通过控件列表遍历反查索引(Kivy的children列表默认逆序存储控件,很容易返回错误结果)。最高效可靠的方式是:创建Button实例时,直接把对应索引作为自定义属性绑定到按钮对象上,点击触发回调时直接从传入的控件实例上读取该属性即可。

完整可运行代码

Python 部分

from kivymd.app import MDApp
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class AddItems(GridLayout):
    def __init__(self, **kwargs):
        super(AddItems, self).__init__(**kwargs)
        for i in range(5):
            # 原示例未给Button设置height,size_hint_y为None时按钮高度为0会不可见,这里补了height参数
            b = Button(text=str(i+1), size_hint=(1, None), height=50)
            # 给当前按钮绑定自定义索引属性,存储循环中对应的i值
            b.btn_index = i
            # 绑定点击事件回调
            b.bind(on_press=self.on_button_press)
            self.add_widget(b)

    def on_button_press(self, instance):
        # 直接从触发事件的按钮实例上读取提前存储的索引
        print(f"被按下的按钮索引值:{instance.btn_index}")

class MainApp(MDApp):
    pass

if __name__ == "__main__":
    MainApp().run()

KV 部分

Scroll:

<Scroll@ScrollView>:
    AddItems:
        size_hint: 1, None
        height: self.minimum_height

<AddItems>:
    cols: 1
    spacing: 10

方案说明

  • 绑定的自定义属性btn_index是直接挂在控件实例上的,后续修改按钮text、调整控件样式都不会影响索引值的准确性
  • 不需要额外维护字典/列表做控件和索引的映射,没有额外的内存开销
  • 点击回调的参数instance就是触发事件的按钮控件本身,直接读属性的逻辑时间复杂度为O(1),效率远高于遍历匹配

内容的提问来源于stack exchange,提问作者Adrian Barbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:12:27