2016-09-22 68 views
0

我想更改按下按钮时启动的功能。已绑定按钮on_press

的Python文件:

class UpdateScreen(Screen): 

swimbot = {} 
def swimbot_connected(self): 
    wallouh = list(AdbCommands.Devices()) 
    if not wallouh: 
     self.ids['text_label'].text = 'Plug your Swimbot and try again' 
    else: 
     for devices in AdbCommands.Devices(): 
      output = devices.serial_number 
      if re.match("^(.*)swimbot", output): 
       self.ids['mylabel'].text = 'Etape 2: Do you need an update ?' 
       self.ids['action_button'].text = 'Check' 
       self.ids['action_button'].bind(on_press = self.check_need_update()) 
      else: 
       self.ids['text_label'].text = 'Plug your Swimbot and try again' 

千伏文件:

<UpdateScreen>: 
BoxLayout: 
    id: update_screen_layout 
    orientation: 'vertical' 
    Label: 
     id: mylabel 
     text: "Etape 1: Connect your Swimbot" 
     font_size: 26 
    Label: 
     id: text_label 
     text: "Truc" 
     font_size: 24 
    FloatLayout: 
     size: root.size 
     pos: root.pos 
     Button: 
      id: action_button 
      pos_hint: {'x': .05, 'y':.25} 
      size_hint: (.9, .4) 
      text: "Try" 
      font_size: 24 
      on_press: root.swimbot_connected() 

但我认为这不是做这种正确的做法:

self.ids['action_button'].bind(on_press = self.check_need_update()) 

有了,我直接去到check_need_update(),它不会等待我按下按钮。

回答

0

当你在python中的函数后面加上()时,你可以执行该函数。所以,当你键入

self.ids['action_button'].bind(on_press = self.check_need_update()) 

你实际上将self.check_needed_update的结果传递给on_press。所以你需要:

self.ids['action_button'].bind(on_press = self.check_need_update) 

这是不同的kv语言。在绑定函数时,实际上需要放置()。您也可以将参数放在那里,当回调被调用时(而不是在定义被读取时)将被评估。

但python代码实际上不会做你想做的。它会将一个附加功能绑定到该按钮,但不会覆盖其他功能。您可以取消绑定回调,但有点复杂(请参阅the documentation here)。

class UpdateScreen(Screen): 

    state = 0 
    swimbot = {} 
    def swimbot_connected(self): 
     if state == 0: 
      self._original_swimbot_connected() 
     if state == 1: 
      self.check_need_update 

然后,而不是解除绑定和新的功能结合到该按钮,你可以只修改UpdateScreen.state

相反,它表现不同我会改变的方式调用的函数。