Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

function - kivy python passing parameters to fuction with button click

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.my_function('btn1')

but I would like to do it in python, as I would like to create a larger number of buttons with a loop. Currently I call my function in python like this:

Button(on_press=self.my_function)

but as I said, if I try to pass a parameter to the function like this, I get an 'AssertionError: None is not callable', like this:

Button(on_press=self.my_function('btn1'))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...