You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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)

关键说明

  1. 保留控件对象:不要将Entry控件转为字符串,直接存储控件对象,后续通过get()方法获取用户输入。
  2. 提取输入内容:在提交函数中,用控件名.get()获取输入框文本,若需要去掉默认提示文本,可使用replace方法过滤。
  3. 正确传递SQL参数:将获取到的输入内容以元组形式传递给execute方法,确保插入数据库的是用户实际输入的值。

内容的提问来源于stack exchange,提问作者Ethan Fuller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:45:30