2015-04-30 71 views
0

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

生成按钮的代码很好地工作,没有问题。我的问题是,当我分配一个on_press或其他事件,以激发我的main.py中的方法。

main.py snippet;

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

创建在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)