【问题标题】:How can I take an input from an entry widget and enter it into a sqlite3 database?如何从条目小部件中获取输入并将其输入到 sqlite3 数据库中?
【发布时间】:2018-02-19 06:01:40
【问题描述】:

我一直在阅读使用 get() 是执行此操作的最佳方法,但我不确定如何使用它,其他答案对我没有帮助。 以下是代码的主要部分。我正在使用 python 3.6、tkinter 和 sqlite3。

import sqlite3
import tkinter as tk
from tkinter import Frame, Tk, Button, Label, Entry, N, S, E, W
from tkinter import TOP, BOTTOM, LEFT, RIGHT, END, ALL

top=Tk()
top.geometry("320x225")
top.title('dvd rentals')
medium_font=('Veranda', 10)
textFrame=Frame(top)

loaneeID=Label()
loaneeID=Label(top,font=medium_font,text='Loanee ID ')
loaneeID.grid(row=2, column=1)
entry1=Entry(textFrame)
entry1=Entry(top, bd = 5, font=medium_font, width=25)
entry1.grid(row=2, column=2)

submit_button = tk.Button(top, text='Add Item', width=8,
                            command=lambda: add_item(top))
submit_button.grid(row=8, column=1, sticky=E, pady=20, padx=20)

top.mainloop()

def main():
    conn = sqlite3.connect('dvd.db')
    c=conn.cursor()

def tableCreate(c):
    c.execute('CREATE TABLE IF NOT EXISTS loanee (loaneeID int, name text, email text)')
    c.execute('CREATE TABLE IF NOT EXISTS dvd (dvdID int, name text)')
    c.execute('CREATE TABLE IF NOT EXISTS loan (loaneeID int, dvdID int, start date text, end date text)')

def insertValues(c, loanee, dvd, loan):
    c.execute('INSERT INTO loanee VALUES (?,?,?)',loanee)
    c.execute('INSERT INTO dvd VALUES (?,?)',dvd)
    c.execute('INSERT INTO loan VALUES (?,?,?,?)',loan)

    tableCreate(c)

    insertValues(c, loanee, dvd, loan)

    conn.commit()
    conn.close()
main()

我的目标是用户输入他们的 ID(和其他条目),他们可以使用指定的提交按钮将其添加到数据库中。

【问题讨论】:

    标签: python python-3.x tkinter sqlite


    【解决方案1】:

    是的,使用Entry小部件的get()方法来获取小部件的当前内容。

    您需要将add_item() 函数添加到您的代码中,然后使用类似于此的代码获取用户的条目:

    def add_item():
        loanee_id = entry1.get()
        print(loanee_id)
    

    然后你需要调用你的 SQL 函数来插入数据。

    请注意,您的代码存在一些问题,首先是top.mainloop() 行之后的代码在您关闭 Tk 窗口之前不会执行。 SQL函数的逻辑也不正确。

    您应该阅读如何组织您的 Tk 应用程序以使用类,因为这将使您的代码更易于管理和使用。

    【讨论】:

    • 所以这需要在按钮之前添加,但与 tkinter 的其余部分一起,对吧?
    • 另外,使用上面的代码会导致一个错误,说没有定义loanee_id。
    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 2017-11-01
    • 2017-07-08
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多