Reputation: 51
I want to have a tkinter gui that has an entry widget along with a button that a user can enter a number into the entry field then click the "submit" button. When the button is pressed I want his entry to store to a database I have set up.
my code so far is as follows:
db = Mysqldb.connect('localhost', 'root', '----', '----', 'design')
cursor = db.cursor()
def submit_it():
cursor.execute('INSERT INTO time VALUES (data.get())')
data = Entry(gui2, text = 'food name')
data.place(x=100,y=100)
submit = Button(gui2, text = 'submit', command = submit_it())
submit.place(x=200,y=200)
any ideas on how I could get this to work would be greatly appreciated... again, all I am wanting to do is have the user input something into the entry field and click the submit button. when this is done his entry will get saved into my database :)
Upvotes: 0
Views: 16510
Reputation: 1
For python 3.7 you should not call the submit_it()
function, instead keep it as submit_it
.
For passing user input use %s instead of directly using data.get().
db = Mysqldb.connect('localhost', 'root', '----', '----', 'design')
cursor = db.cursor()
user_input = data.get()
def submit_it():
cursor.execute('INSERT INTO time VALUES (%s)', user_input)
data = Entry(gui2, text = 'food name')
data.place(x=100,y=100)
submit = Button(gui2, text = 'submit', command = submit_it)
submit.place(x=200,y=200)
For inserting multiple values at a time, pass list or tuple of variables that has user input values in it.
Multiple value insert example:
# suppose you have 3 inputs as name, quantity, color
# then use...
Name = name.get()
Quantity = quantity.get()
Color = color.get()
def submit_it():
cursor.execute('INSERT INTO time(name, quantity, color)VALUES (%s, %s, %s)', (Name, Quantity, Color))
Also, to successfully add the values to the database, u should db.commit()
and db.close()
Upvotes: 0
Reputation: 33704
Two things you will need to change, place data.get() as a parameter and not directly in the operation. And don't call submit_it when passing it as a command for the button.
db = Mysqldb.connect('localhost', 'root', '----', '----', 'design')
cursor = db.cursor()
def submit_it():
cursor.execute('INSERT INTO time VALUES (%s)', (data.get(),)) # place data.get() as a parameter as a type or list
data = Entry(gui2, text = 'food name')
data.place(x=100,y=100)
submit = Button(gui2, text = 'submit', command = submit_it) # don't call submit_it, get rid of the ()
submit.place(x=200,y=200)
You probably also want to commit and close the database later using db.commit()
and db.close()
to save the changes.
Upvotes: 1