问题
In the below code two tkinter entry is created entry1 and entry2 respectively for username and password. What I am looking for is storing the value entered in the tkinter entry to the database table admin_details. But nothing is passed. Also I have no idea in using the condition i.e. " retrieve the values inserted in the tkinter entry and store the data inside the table after the button Login is pressed." Code is something like below:
import MySQLdb as mdb
from Tkinter import *
from tkMessageBox import *
root = Tk()
test=StringVar()
label1=Label(root,text='Username').grid()
entry1 = Entry(root, textvariable='uname')
entry1.grid()
label2=Label(root,text='password').grid()
entry2 = Entry(root, textvariable='pword')
entry2.grid()
print entry2
uname = entry1.get()
pword= entry2.get()
tup=[uname,pword]
option1 = Button(root, text = 'Login', command = next)
option1.grid()
if uname!='':
def next():
con = mdb.connect('localhost', 'root', 'root', 'kuis');
with con:
cur = con.cursor()
insert_sql = 'INSERT INTO admin_details(username, password) VALUES("{0}","{1}")'.format(*tup)
cur.execute(insert_sql)
root.mainloop()
回答1:
The obvious problem is you are getting the text from both Entries directly after they have been initialized. The two variables you are using for this will not be changed when the Text in the Entries changes.
Here is some basic code how to retrieve the values from the two entry fields and pass them to a function:
import tkinter as Tk
import tkinter.messagebox
def show_pass_user(password, user):
# show what we got
tkinter.messagebox.showinfo("Data received", "Hey just got your username \"" + user + "\"" +
" and password \"" + password + "\"")
# run your sql here
def main():
root = Tk.Tk()
entry_user = Tk.Entry(root)
entry_user.insert(0, "Username")
entry_pass = Tk.Entry(root)
entry_pass.insert(0, "Password")
# use a lambda to get Username and Password when button is pressed
pressme = Tk.Button(root, text="Press Me", command=lambda:
show_pass_user(entry_pass.get(), entry_user.get()))
entry_user.grid()
entry_pass.grid()
pressme.grid()
root.mainloop()
if __name__ == "__main__":
main()
This code runs only with Python3!
来源:https://stackoverflow.com/questions/27875238/after-the-login-button-is-pressed-how-to-obtain-the-value-of-tkinter-entry-and