kivy python passing parameters to fuction with button click

后端 未结 1 1105
难免孤独
难免孤独 2021-01-07 05:38

I am having trouble passing parameters to function when calling it with button press. One could do it like this in kivy language:

Button: 
   on_press: root.         


        
相关标签:
1条回答
  • 2021-01-07 06:15
    Button(on_press=self.my_function)
    

    This is passing the function as an argument.

    Button(on_press=self.my_function('btn1'))
    

    This is calling the function and passing the returned value as the argument to on_press. Since the returned value is None, you get your error.

    You instead need to pass a new function that calls your normal function and automatically passes the argument. In general, it's convenient to use functools.partial:

    from functools import partial
    Button(on_press=partial(self.my_function, 'btn1'))
    

    You can also use a lambda function:

    Button(on_press=lambda *args: self.my_function('btn1', *args))
    
    0 讨论(0)
提交回复
热议问题