如何获取存储在 sqlite3 数据库中的数据并将其分配给 tkinter 中的变量 python

how to fetch data stored in sqlite3 database and assign it to the variables in tkinter python

在下面的代码中,我将 value1 和 value2 保存到 sqlite3 数据库中,并将 txt_ 保存到名为 data 的文件夹中。 我在这里想要实现的是,当我重新运行程序并打开文件时,txt_ 文件应该在文本区域中打开,其中包含我保存时添加的行。当我单击添加按钮时,应该更新 value1 和 value2 并且新创建的行应该在下一行。 让我知道我的方法是否正确,如果不正确请告诉我更好的方法。

代码:

from tkinter import *
from tkinter import messagebox
import sqlite3
import os

root = Tk()
root.geometry('400x400')

var_e = StringVar(None)
def create_my_db():
    conn = sqlite3.connect(database=r'my db.db')
    cur = conn.cursor()
    cur.execute("""CREATE TABLE IF NOT EXISTS "myLogs"
                (
                    "int_value" INTEGER,
                    "float_value" REAL
                )
                """)
    conn.commit()
create_my_db()

def add_lbl():
    global value1, value2
    value1 += 1
    value2 += 1
    sample = f'This is line {value1} which has value of {value2}\n'
    txt_.insert(END, sample)

def save():
    conn = sqlite3.connect(database=r'my db.db')
    cur = conn.cursor()
    cur.execute("""INSERT INTO myLogs VALUES (?,?)""",
                (
                    value1,
                    value2
                )
                )
    conn.commit()

    # labels to check if the values are stored in the database
    values_lbl.config(text=f'value 1 is [ {value1} ] & value 2 is [ {value2} ]')

def save_txt():
    file_txt = open(f'data/{value1}.txt', 'w')
    file_txt.write(txt_.get(1.0, END))
    file_txt.close()
    messagebox.showinfo('SAVED', 'Data saved to the database.')

def open_():
    for txt_file in os.listdir("data/"):
        if txt_file.split('.')[0] == f'{var_e.get()}':
            file_ = open(f"data/{txt_file}", "r")
            for i in file_:
                txt_.insert(END, i)
            file_.close()

value1 = 0
value2 = 0.9

values_lbl = Label(root, text=f'value 1 is [ {value1} ] & value 2 is [ {value2} ]')
values_lbl.pack()

btn_frame = Frame(root)
btn_frame.pack()

btn_add = Button(btn_frame, text='Add', command=add_lbl)
btn_add.pack(side=LEFT)

e = Entry(btn_frame, textvariable=var_e)
e.pack(side=LEFT)

btn_open = Button(btn_frame, text='Open', command=open_)
btn_save = Button(btn_frame, text='Save', command=lambda:[save(), save_txt()])
btn_open.pack(side=LEFT)
btn_save.pack(side=LEFT)

txt_ = Text(root)
txt_.pack(fill=BOTH, expand=True)

root.mainloop()

当我发布这个问题时,我不知道如何 运行 更新 value1 和 value2 的查询,这就是为什么我没有在 open_() 函数中提到查询。现在我知道应该如何完成该查询了。所以在下面的代码中,我将查询添加到 open_() 函数。现在完整的程序 运行 没问题了。

def open_():
    global value1, value2
    txt_.delete(1.0, END)
    for txt_file in os.listdir("data/"):
        if txt_file.split('.')[0] == f'{var_e.get()}':
            file_ = open(f"data/{txt_file}", "r")
            for i in file_:
                txt_.insert(END, i)
            file_.close()

    conn = sqlite3.connect(database=r'my db.db')
    cur = conn.cursor()

    cur.execute("""SELECT * FROM myLogs WHERE int_value=?""", (var_e.get(),))
    row = cur.fetchone()
    if row is None:
        messagebox.showerror("ERROR", 'Invalid input.')
    else:
        value1 = row[0]
        value2 = row[1]
    conn.commit()