首页 > 解决方案 > 通过按下按钮 Tkinter/sqlite 从条目标签插入数据库

问题描述

这是我在 Tkinter 中的标签和输入框(仅用于客户姓名,其他输入看起来相似)。我的目标是在这个输入框中输入一些单词,然后按“保存”按钮将其插入数据库。

conn = sqlite3.connect('my_database.db')
cur = conn.cursor()
CustomerName = StringVar()

lblName = Label(bottomLeftTopL, font = ('arial', 16, 'bold'), text = "Name", fg 
= 'black', width = 15, bd = 10, anchor = 'w')
lblName.grid(row = 0, column = 0)

txtName = Entry(bottomLeftTopL, font = ('arial', 16, 'bold'), bd = 2, width = 
24, bg = 'white', justify = 'left', textvariable = CustomerName)
txtName.grid(row = 0, column = 1)

我想用来将输入保存到数据库中的按钮。

btnSave = Button(bottomLeftBottomL, pady = 8, bd = 2, 
fg = 'black', font = ('arial', 10, 'bold'), width = 10, text = "Save",
bg = 'white').grid(row = 7, column = 1)

这是我在 SQLAlchemy 中的客户表类。

class Customers(Base):
    __tablename__ = "customers"

    id_customer = Column(Integer, primary_key = True)
    name = Column(String)
    phone_number = Column(String)
    adress = Column(String)

    def __init__(self, name, phone_number, adress):
       self.name = name
       self.phone_number = phone_number
       self.adress = adress

我想我需要使用游标和“插入”语句。有人可以帮我编写这个操作的函数吗?

标签: pythonsqlitetkintersqlalchemy

解决方案


这是您尝试完成的最小示例 - 按下按钮时将条目中的值插入到 db 中。对此很重要的两个主要概念是

  1. command按钮的选项 - 当它被点击时调用一个函数
  2. get条目小部件的方法,该方法返回小部件中的文本。
from tkinter import *
import sqlite3
root = Tk()
conn = sqlite3.connect('my_database.db')
#create a table for testing
sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS my_table (
                                        name text
                                    ); """
conn.execute(sql_create_projects_table)

#function to be called when button is clicked
def savetodb():
    #txtName.get() will get the value in the entry box
    entry_name=txtName.get()
    conn.execute('insert into my_table(name) values (?)', (str(entry_name),))
    curr=conn.execute("SELECT name from my_table")
    print(curr.fetchone())

txtName = Entry(root)
txtName.pack()

#function savetodb will be called when button is clicked
btnSave = Button(root ,text = "Save",command=savetodb)
btnSave.pack()

root.mainloop()

推荐阅读