通过按下按钮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

我想我需要使用光标和"插入"语句。有人能帮我写这个操作的函数吗?

这是您试图实现的一个最小示例-当按下按钮时,在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()

最新更新