在on_press上绑定一个按钮

时间:2016-09-22 14:47:21

标签: python button kivy bind

我想更改按下按钮时启动的功能。

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'

Kv档案:

<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(),它不等我按下按钮。

1 个答案:

答案 0 :(得分: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,而不是将新功能解除绑定并绑定到按钮上。