使用Tkinter和SQLite3创建登录窗口时数据库插入异常求助
问题原因及解决方法
你的代码存在两个核心错误,导致数据库存入的是控件标识而非用户实际输入内容:
错误1:将Entry控件直接转为字符串
你执行了username = str(username)和password = str(password),这会把Tkinter的Entry控件对象转换成它的内部标识字符串(比如.!toplevel.!entry),而非用户输入的文本。正确做法是通过控件的get()方法获取输入内容。错误2:SQL插入参数传递错误
submit1函数里的SQL参数写的是字符串"username, password,",这不是引用变量,而是直接把这个字符串作为值插入数据库。需要改为传递用户输入的实际内容作为参数。
修正后的代码
def createlogin(): global username_entry, password_entry # 存储控件对象,而非字符串 top= Toplevel() top.title("SmartCards - New User") top.iconbitmap(r"C:\Users\Ethan\Documents\Comp NEA\Icon.ico") top.config(padx=50, pady=50, bg=BACKGROUND_COLOR) def submit1(): # 获取输入框的实际内容,可移除默认提示文本 user_name = username_entry.get().replace("Username: ", "") pass_word = password_entry.get().replace("Password: ", "") # 用实际输入内容作为参数执行SQL插入 c.execute("INSERT INTO login (username, password) VALUES (?, ?)", (user_name, pass_word)) conn.commit() username_entry = Entry(top) username_entry.insert(0,"Username: ") username_entry.grid(row=0, column=0) # 移除str(username)这行代码 password_entry = Entry(top) password_entry.insert(0,"Password: ") password_entry.grid(row=1, column=0) # 移除str(password)这行代码 submit = Button(top, text="Submit", command=submit1) submit.grid(row=2, column=0)
关键说明
- 保留控件对象:不要将Entry控件转为字符串,直接存储控件对象,后续通过
get()方法获取用户输入。 - 提取输入内容:在提交函数中,用
控件名.get()获取输入框文本,若需要去掉默认提示文本,可使用replace方法过滤。 - 正确传递SQL参数:将获取到的输入内容以元组形式传递给
execute方法,确保插入数据库的是用户实际输入的值。
内容的提问来源于stack exchange,提问作者Ethan Fuller
相关产品推荐
相关产品推荐

