Search code examples
pythonsqlitetkinterttk

Python tkinter - retrieve SQLite ID from ttk.combobox


I have a ttk.combobox populated with data from database. When user choose the data I need to retrieve ID of chosen data.

I have a solution for this but I'm sure there is a more elegant and simple solution for this but i can't find one. I split SQL row ID with the '.', than from Combobox I turn string into list split by '.' and retrieve list[0] for ID.

Code sample:

from tkinter import *
from tkinter import ttk
import sqlite3
import DataBasePM

DBProjectManager2=DataBasePM.DBProjectManager2

def DropDownProjectView():
    con=sqlite3.connect(DBProjectManager2)
    con.row_factory = lambda curs, row:str(row[0])+". "+ row[1] #split ID with '.' 
    curs= con.cursor()
    curs.execute( """SELECT idProject, ProjectName 
                FROM Project WHERE idStatus=1""")
    rows=curs.fetchall()
    con.close()
    return rows

def GetIDFromDropDown(pickedString):
                 GetID=pickedString
                 GetID = list(GetID.split(".")) #id is before '.'
                 GetID=(int(GetID[0])) 
                 print(GetID)


root = Tk()
root.title("Tkinter ex")
root.geometry("400x400")

project_name_drop =  ttk.Combobox (root, value=DropDownProjectView() )
project_name_drop.pack()

buttonA=Button(root, text="get ID",command=lambda: GetIDFromDropDown(project_name_drop.get()))
buttonA.pack()

root.mainloop()

Solution

  • You can return dictionary instead of list from DropDownProjectView():

    def DropDownProjectView():
        con=sqlite3.connect(DBProjectManager2)
        # return two items in each record: dropdown-item, id
        con.row_factory = lambda curs, row: (str(row[0])+". "+row[1], row[0])
        curs= con.cursor()
        curs.execute("SELECT idProject, ProjectName FROM Project WHERE idStatus=1")
        # build a dictionary with dropdown-item as key and id as value
        rows = {r[0]:r[1] for r in curs}
        con.close()
        return rows
    

    Then use list(rows.keys()) as the dropdown items:

    rows = DropDownProjectView()
    project_name_drop =  ttk.Combobox (root, value=list(rows.keys()))
    project_name_drop.pack()
    

    Finally, use rows[pickedString] to get the ID in GetIDFromDropDown():

    def GetIDFromDropDown(pickedString):
        # cater exceptional case
        if pickedString in rows:
            id = rows[pickedString]
            print(id)
        else:
            print("invalid option: '%s'" % pickedString)