0

I'm trying to make a small program that saves data into a sqlite database. The thing is that I'm not being able to insert any data but empty inserts. I don't know what I'm doing wrong.

Thanks in advance! Here is my code.

class Vista(Frame):
    def __init__(self, master):
        Frame.__init__(self,master)
        self.grid()
        self.pack()
        self.create_widgets()

    def insertar(self, n, v):
        try:
            cursor.execute('''INSERT INTO passwords (name, value) VALUES (?,?)''', (n.get(), v.get()))
            con.commit()
        except Exception as e:
            # Roll back any change if something goes wrong
            con.rollback()
            print "Error %s;" %e.args[0]
            sys.exit(1)

        finally:
            if con:
                con.close()

    def create_widgets(self):
        self.title_nombre = Label(self, text="Nombre:")
        self.title_nombre.grid(row = 1, column = 1, sticky = W, pady=(10, 0))
        nom = StringVar()
        pas = StringVar()
        self.nombre = Entry(self, textvariable=nom)
        self.nombre.grid(row = 1, column = 2, sticky = W, pady=(10, 0))
        self.title_passwd = Label(self,text="Password:")
        self.title_passwd.grid(row = 2, column = 1, sticky = W)
        self.passwd = Entry(self, textvariable= pas)
        self.passwd.grid(row = 2, column = 2, sticky = W)
        self.boton = Button(text="Añadir", command=self.insertar(nom, pas))
        self.boton.grid(columnspan=1, row=3, sticky = W, pady=(10,0), padx=(5,0))

root = Tk()
root.title("Contraseña")
root.geometry("250x150")

root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
app = Vista(root)
app.grid(column=0, row=0)
app.columnconfigure(0, weight=1)
app.rowconfigure(0, weight=1)

app.mainloop()

1 Answer 1

4

The issue is with this line:

self.boton = Button(text="Añadir", command=self.insertar(nom, pas))

command=self.insertar(nom, pas) first calls self.insertar(nom, pas) and then passes command as the result of that function call. You want to pass a function to command:

def insert_command():
    return self.insertar(nom, pas)

self.boton = Button(text="Añadir", command=insert_command)

Or do it in one line:

self.boton = Button(text="Añadir", command=lambda: self.insertar(nom, pas))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I didn't know how to apply the first one but the second one worked just fine. I don't understand whyit works that way.
@Francisco: They both should work fine. The second one is a shorter version of the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.