在tkinter列表小部件中列出数据并隐藏主索引,但仍将其用于

时间:2020-08-11 16:21:46

标签: python sqlite tkinter

我已经创建了一个sqlite3数据库:

def connect():
    conn=sqlite3.connect("todo.db")
    cur=conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS todo (id INTEGER PRIMARY KEY, tasks TEXT, typ TEXT, difficulty TEXT, frequency TEXT, deadline TEXT)")
    conn.commit()
    conn.close()

我从中获取数据:

def view():
    conn=sqlite3.connect("todo.db")
    cur=conn.cursor()
    cur.execute("SELECT * FROM todo")
    rows=cur.fetchall()
    conn.close()
    return rows

并在tkinter列表小部件中显示它们:

def view_command():
    list1.delete(0,END)
    for row in tdo.view():
        row = str(row).strip("()")
        row = row.replace("'","")
        row = row.strip()
        list1.insert(END,row)

它按预期显示了行的所有元素:

12,完成某件事,要做,困难,经常是2020年12月12日

现在我要做的是在列表中显示不包含索引的行:

完成某事,待办事项,困难,通常是在2012年12月12日

我这样做是通过不从数据库中选择id来实现的,我试图通过strip和类似的函数将其排除。但随后ID丢失了。我希望能够通过ID选择该行以进一步使用它。

def get_selected_row(event):
    try:
        global selected_tuple
        index=list1.curselection()[0]
        selected_tuple=list1.get(index)
        selected_tuple = tuple(selected_tuple.split (","))

因此,简而言之,如何从数据库中获取索引,如何将索引隐藏在列表小部件中,但是在选择索引时仍可以使用它?

1 个答案:

答案 0 :(得分:1)

您可以创建一个映射文件,以将列表框索引映射到数据库ID。

以下示例假定数据库id是行的第一个元素。

def view_command():
    list1.mapping = []
    list1.delete(0,END)
    for row in tdo.view():
        db_id = row.pop(0)
        list1.mapping.append(db_id)
        row = str(row).strip("()")
        row = row.replace("'","")
        row = row.strip()
        list1.insert(END,row)

现在,给定列表框中的索引x,数据库ID将为list1.mapping[x]


不是将列表转换为字符串,然后删除转换添加的字符,为什么不只使用逗号和空格将列表连接起来?

例如:

row = ", ".join(row)