简体   繁体   English

Python, Kivy, "AssertionError: None is not callable" function 按钮调用错误

[英]Python, Kivy, "AssertionError: None is not callable" Error on function call by button

So I whant to use this code to call a function on a button press:所以我想使用此代码在按下按钮时调用 function:

botao_ok.bind(on_press=f_adicionar_socios(txt_n_socio.text,txt_nome.text,txt_filho_de.text,txt_filho_e_de.text,txt_data_nas.text,txt_tipo_ID.text,txt_num_ID.text,txt_NIF.text,txt_morada_rua.text,txt_morada_localidade.text,txt_codigo_postal.text,txt_tel_fixo.text,txt_telemovel.text,txt_email.text,txt_tipo_socio.text,txt_data_admicao.text,txt_zona.text,txt_actividade.text,txt_actividade_de.text,txt_actividade_ate.text,txt_observacoes.text))

But to keep it simple, I only need to solve this problem:但为了简单起见,我只需要解决这个问题:

#My Function
def teste_(nome):
    print nome
#Button
botao_ok.bind(on_press=teste_('Ola'))
# Button is inside a Class MYApp

and it gives the error: AssertionError: None is not callable它给出了错误:AssertionError: None is not callable

Ive tryied everything I tough off and can't solve this... Thank you我已经尝试了所有我遇到的困难,但无法解决这个问题......谢谢

When you write teste_('Ola') the function runs and returns None当你写teste_('Ola')函数运行并返回None

So when you write所以当你写

botao_ok.bind(on_press=teste_('Ola'))

It actually gets set to:它实际上被设置为:

botao_ok.bind(on_press=None)

Which in short is causing your problem.简而言之,这导致了您的问题。

In order to get it to call teste_('Ola') When the button is pressed, you could use a lambda function:为了让它在按下按钮时调用teste_('Ola') ,您可以使用 lambda 函数:

botao_ok.bind(on_press=lambda x:teste_('Ola'))

In case your function call doesn't require any arguments, you can write the name of the function without parentheses or a lambda:如果您的 function 呼叫不需要任何 arguments,您可以写下不带括号的 function 的名称或 lambda:

function_caller.bind(on_press=your_function)

this works because python considers functions as first-class values, just like a string, an integer or a float.这是可行的,因为 python 将函数视为一等值,就像字符串、integer 或浮点数一样。

(this answer is here for the people that have a similar problem and want cleaner code, the correct answer in this exact situation is what Vincent described above) (这个答案是为那些有类似问题并想要更清晰代码的人准备的,在这种情况下的正确答案就是文森特上面描述的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM