通过按下按钮Tkinter / sqlite

时间:2019-01-11 23:24:06

标签: python sqlite tkinter sqlalchemy

这是我在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

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

1 个答案:

答案 0 :(得分:0)

这是您要完成的工作的一个最小示例-按下按钮时,将值插入db的条目中。对此很重要的2个主要概念是

  
      按钮的
  1. command选项-单击该函数时会调用一个函数,并且
  2.   输入窗口小部件的
  3. get方法,返回窗口小部件中的文本。
  4.   
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()