简体   繁体   中英

List data in tkinter list widget and hide primary index but still use it for

I have created a sqlite3 database:

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()

I fetch the data from it:

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

and show them in a tkinter list widget:

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)

It shows all elements of the rows as expected:

12, finish something, todo, difficult, often, 12.08.2020

Now what I'm trying to do is to show this row in the list without index:

finish something, todo, difficult, often, 12.08.2020

I did this by not selecting the id from the database, and I tried to exclude it with strip and similar functions. But then the id gets lost. I want to be able to select the row by the id to further work with it.

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

So to make it short, how can I get the index from the database, hide the index in the list widget, but still be able to use it with when selecting it?

You can create a mapping file to map a listbox index to a database id.

The following example assumes that the database id is the first element of a row.

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)

Now, given index x from the listbox, the database id would be list1.mapping[x] .


Instead of converting the list to a string and then removing characters added by the conversion, why not just join the list with a comma and space?

For example:

row = ", ".join(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM