按下登录按钮后,如何获取Tkinter entry的值并传递给SQL查询? [英] After the login Button is pressed, how to obtain the value of Tkinter entry and pass it to the SQL query?

查看:29
本文介绍了按下登录按钮后,如何获取Tkinter entry的值并传递给SQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,分别为用户名和密码创建了两个 tkinter 条目 entry1 和 entry2.我正在寻找的是将在 tkinter 条目中输入的值存储到数据库表 admin_details.但什么都没有通过.此外,我不知道使用条件,即在按下登录按钮后检索插入到 tkinter 条目中的值并将数据存储在表中."代码如下:

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

推荐答案

明显的问题是您在两个条目初始化后直接从它们获取文本.当条目中的文本更改时,您为此使用的两个变量不会更改.

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

此代码仅适用于 Python3!

这篇关于按下登录按钮后,如何获取Tkinter entry的值并传递给SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆