Function running without Python button click

0

Good evening, My callbackInsereCritical function runs directly without the click of the button, what can it be?

def callbackInsereCritico(nome):
  conn = psycopg2.connect(host='localhost',
                        database='diet+',
                        user='postgres',
                        password='teste')

  cur = conn.cursor()
  curCritics = conn.cursor()
  cur.execute("INSERT INTO critico (nome) VALUES ('" + nome + "')")                              
  conn.commit() 



rotuloAv = Label(formulario, text = "Cadastro do Avaliador")
rotuloNm = Label(formulario, text = "Nome:")
texto9 = Entry(formulario)
botaoAv =  Button(formulario, text = "Cadastrar",command = callbackInsereCritico(texto9.get())) 
resultadoAv = Label(formulario, text = None)
    
asked by anonymous 26.03.2018 / 00:29

1 answer

0

You are not going through a function the way you are doing it. Instead, you are executing the callbackInsereCritico function and passing the return value to the command attribute. That's why it's running without the click event.

Imagine that you have this function:

def fazalgo():
    return "fizalgo"

If you run:

type(fazalgo)

The return will be:

<type 'function'>

Now if you run:

type(fazalgo())

The return will be:

<type 'str'>

Did you notice the difference? In the first case, the function type received a function as a parameter, and in the second, it received the function return.

Now, since you need to pass an argument to the function, you can not simply do: command = callbackInsereCritico .

It has a pythonic way of doing this:

command = lambda: callbackInsereCritico(texto9.get())

lambda in Python is just a more elegant way of declaring functions. They are very useful for certain times like this.

So, your code stays:

def callbackInsereCritico(nome):
  conn = psycopg2.connect(host='localhost',
                        database='diet+',
                        user='postgres',
                        password='teste')

  cur = conn.cursor()
  curCritics = conn.cursor()
  cur.execute("INSERT INTO critico (nome) VALUES ('" + nome + "')")                              
  conn.commit() 



rotuloAv = Label(formulario, text = "Cadastro do Avaliador")
rotuloNm = Label(formulario, text = "Nome:")
texto9 = Entry(formulario)
botaoAv =  Button(formulario, text = "Cadastrar", command = lambda: callbackInsereCritico(texto9.get()))
resultadoAv = Label(formulario, text = None)

How to explain lambda here goes beyond the scope of the question, I leave here this link: link

    
26.03.2018 / 00:58