首页 > 解决方案 > 如何获取kivy中按下的按钮的ID?

问题描述

这是我正在使用的示例代码。

class MainScreen(GridLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.cols = 1
        MainScreenLayout = GridLayout()
        MainScreenLayout.cols = 3
       
       #for loop creating buttons with varying IDs
        NumberToCreate = 4
        for x in range(int(NumberToCreate)):
            aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
            MainScreenLayout.add_widget(aButton)
            self.ids['button' + str(x)] = aButton

        self.add_widget(MainScreenLayout)

    #function for when button is pressed
    def press_auth(self, instance):
        print(str(instance)) #ulimate goal is get ID name and x number, to use later in code
        
class MyApp(App):
    def build(self):
        return MainScreen()
    
if __name__== '__main__':
    MyApp().run()

标签: pythonbuttonkivy

解决方案


kivy 中的 ID 通常与 kv 文件结合使用,以通过继承跟踪对象。您可能不应该ids像您一样将实例变量用作 setter,因为它通常在内部设置为 kivy 并被开发人员用作 getter。

一种更简单的方法是在每个 Button 实例上设置一个任意变量并跟踪那里的差异。如果您打算使用深度继承,这就是您想要使用的原因,ids那么我会id在将实例添加到MainScreen.

第一种方法可以像这样简单地完成:

class MainScreen(GridLayout):

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        self.cols = 1
        MainScreenLayout = GridLayout()
        MainScreenLayout.cols = 3
       
       #for loop creating buttons with varying IDs
        NumberToCreate = 4
        for x in range(int(NumberToCreate)):
            aButton = Button(text='button text ' + str(x), on_press=self.press_auth)
            aButton.my_id = x  # or 'button' + str(x) or whatever you want to use to track buttons
            MainScreenLayout.add_widget(aButton)

        self.add_widget(MainScreenLayout)

    #function for when button is pressed
    def press_auth(self, instance):
        print(str(instance.my_id)) #ulimate goal is get ID name and x number, to use later in code
        
class MyApp(App):
    def build(self):
        return MainScreen()
    
if __name__== '__main__':
    MyApp().run()

推荐阅读