Kivy Builder - 动态按钮 on_press

Kivy Builder - Dynamic Button on_press

我一直在使用 kivy 创建一个应用程序。在我的应用程序中,我有一个从目录读取的按钮,并为目录中的每个文件添加一个按钮到弹出窗口小部件。

生成按钮的代码运行良好,没有任何问题。我的问题是当我分配一个 on_press 或其他事件时,在我的 main.py.

中触发一个方法

main.py 片段;

    class Container(BoxLayout):
        container=ObjectProperty(None)
        SelectGamePopup = Popup(title='Start A New Game', size_hint=(None, None))
        ...
        def newGame(self):
            BlankLayout = BoxLayout(orientation='vertical')
            BlankGrid = GridLayout(cols=3, size_hint_y=7)
            DismissButton = Button(text='Back', size_hint_y=1)
            DismissButton.bind(on_press=Container.SelectGamePopup.dismiss)

            for files in os.listdir(os.path.join(os.getcwd(), 'Games')):
                addFile = files.rstrip('.ini')
                BlankGrid.add_widget(Builder.load_string('''
Button:
text:''' + "\"" + addFile + "\"" + '''
on_press: root.gameChooser(''' + "\"" + addFile + "\"" + ''')
'''))

            BlankLayout.add_widget(BlankGrid)
            BlankLayout.add_widget(DismissButton)

            Container.SelectGamePopup.content = BlankLayout
            Container.SelectGamePopup.size=(self.container.width - 10, self.container.height - 10)
            Container.SelectGamePopup.open()

        def gameChooser(self, game):
            Container.SelectGamePopup.dismiss
            print(game)

问题在于on_press: root.gameChooser(''' + "\"" + addFile + "\"" + ''')。返回的错误是; AttributeError: 'Button:' object has no attribute 'gameChooser'.

如何让这个动态创建的按钮调用我想要的函数,以及将动态名​​称传递给该函数?

非常感谢!

使用 python 语言创建按钮并使用 on_press 绑定并使用部分

发送参数
from functools import partial 
class Container(BoxLayout):
    container=ObjectProperty(None)
    SelectGamePopup = Popup(title='Start A New Game', size_hint=(None, None))
    ...
    def newGame(self):
        BlankLayout = BoxLayout(orientation='vertical')
        BlankGrid = GridLayout(cols=3, size_hint_y=7)
        DismissButton = Button(text='Back', size_hint_y=1)
        DismissButton.bind(on_press=Container.SelectGamePopup.dismiss)

        for files in os.listdir(os.path.join(os.getcwd(), 'Games')):
            addFile = files.rstrip('.ini')
            # normal button
            MydynamicButton = Button(text=addFile)
            # bind and send 
            MydinamicButton.bind(on_press = partial(self.gamechooser ,addFile)) #use partila to send argument to callback
            BlankGrid.add_widget(MydinamicButton)


        BlankLayout.add_widget(BlankGrid)
        BlankLayout.add_widget(DismissButton)

        Container.SelectGamePopup.content = BlankLayout
        Container.SelectGamePopup.size=(self.container.width - 10, self.container.height - 10)
        Container.SelectGamePopup.open()
    # you can use *args to get all extra argument that comes with on_press in a list
    def gameChooser(self, game ,*args):
        Container.SelectGamePopup.dismiss
        print(game)