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

如何在Kivy框架中获取被点击按钮的ID标识

问题原因

你当前直接打印instance得到内存地址,是因为instance是Button类的实例对象,Python默认打印类实例时会输出「类名+内存地址」的格式,不会自动返回你存在self.ids里的ID名称。

实现方案

方案1:给按钮添加自定义属性(推荐,性能最优)

Python是动态语言,可以直接给按钮实例绑定自定义属性存储你需要的ID信息,不需要额外遍历查找,代码实现最简单。

核心修改点

循环创建按钮时新增自定义属性:

for x in range(int(NumberToCreate)):
    aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
    # 新增自定义属性存储ID
    aButton.btn_id = f"Button {x}"
    MainScreenLayout.add_widget(aButton)
    self.ids['button' + str(x)] = aButton

点击事件直接读取属性即可:

def press_auth(self, instance):
    print(instance.btn_id)

方案2:反向遍历self.ids查找(适配现有存储逻辑)

如果你不想新增自定义属性,要沿用已有的self.ids存储结构,可以通过遍历字典匹配按钮实例拿到对应的ID键名:

def press_auth(self, instance):
    for btn_key, btn_obj in self.ids.items():
        if btn_obj == instance:
            # 转换为你需要的「Button x」格式
            target_id = btn_key.replace('button', 'Button ')
            print(target_id)
            break
完整可运行代码(方案1实现)
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MainScreen(GridLayout):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.cols = 1
        MainScreenLayout = GridLayout()
        MainScreenLayout.cols = 3
       
        NumberToCreate = 4
        for x in range(int(NumberToCreate)):
            aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
            aButton.btn_id = f"Button {x}"
            MainScreenLayout.add_widget(aButton)
            self.ids['button' + str(x)] = aButton

        self.add_widget(MainScreenLayout)

    def press_auth(self, instance):
        print(instance.btn_id)
        
class MyApp(App):
    def build(self):
        return MainScreen()
    
if __name__== '__main__':
    MyApp().run()

内容的提问来源于stack exchange,提问作者Jackson Harvey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:18:05