CyberSkull311
CyberSkull311

Reputation: 45

How can I take an input from an entry widget and enter it into a sqlite3 database?

I've been reading that using get() is the best way to do this, but I'm not sure how to use it, and other answers haven't been helpful to me. The following is the main part of the code. I'm using python 3.6, tkinter and sqlite3.

import sqlite3
import tkinter as tk
from tkinter import Frame, Tk, Button, Label, Entry, N, S, E, W
from tkinter import TOP, BOTTOM, LEFT, RIGHT, END, ALL

top=Tk()
top.geometry("320x225")
top.title('dvd rentals')
medium_font=('Veranda', 10)
textFrame=Frame(top)

loaneeID=Label()
loaneeID=Label(top,font=medium_font,text='Loanee ID ')
loaneeID.grid(row=2, column=1)
entry1=Entry(textFrame)
entry1=Entry(top, bd = 5, font=medium_font, width=25)
entry1.grid(row=2, column=2)

submit_button = tk.Button(top, text='Add Item', width=8,
                            command=lambda: add_item(top))
submit_button.grid(row=8, column=1, sticky=E, pady=20, padx=20)

top.mainloop()

def main():
    conn = sqlite3.connect('dvd.db')
    c=conn.cursor()

def tableCreate(c):
    c.execute('CREATE TABLE IF NOT EXISTS loanee (loaneeID int, name text, email text)')
    c.execute('CREATE TABLE IF NOT EXISTS dvd (dvdID int, name text)')
    c.execute('CREATE TABLE IF NOT EXISTS loan (loaneeID int, dvdID int, start date text, end date text)')

def insertValues(c, loanee, dvd, loan):
    c.execute('INSERT INTO loanee VALUES (?,?,?)',loanee)
    c.execute('INSERT INTO dvd VALUES (?,?)',dvd)
    c.execute('INSERT INTO loan VALUES (?,?,?,?)',loan)

    tableCreate(c)

    insertValues(c, loanee, dvd, loan)

    conn.commit()
    conn.close()
main()

My aim is that user will enter their ID (and other entries), which they can add to the database using the designated submit button.

Upvotes: 1

Views: 1109

Answers (1)

mhawke
mhawke

Reputation: 87134

Yes, use the get() method of the Entry widget to get the current contents of the widget.

You need to add the add_item() function to your code, then get the user's entry using code similar to this:

def add_item():
    loanee_id = entry1.get()
    print(loanee_id)

Then you need to call your SQL functions to insert the data.

Notice that there are a few problems with your code, the first is that the code after the line top.mainloop() will not be executed until you close the Tk window. Also the logic of the SQL functions is incorrect.

You should read up on how to organise your Tk application to use classes because this will make your code more manageable and easier to work with.

Upvotes: 1

Related Questions