我一直在使用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'
。
如何让这个动态创建的按钮调用我想要的函数,以及将动态名称传递给该函数?
非常感谢!
答案 0 :(得分:0)
使用python语言创建按钮并使用on_press绑定并使用partial
发送参数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)