ffuentes
ffuentes

Reputation: 1182

Keep getting empty inserts in Python

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()

Upvotes: 0

Views: 53

Answers (1)

Blender
Blender

Reputation: 298422

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))

Upvotes: 4

Related Questions