Python tkinter - 从 ttk.combobox 检索 SQLite ID

Python tkinter - retrieve SQLite ID from ttk.combobox

我有一个 ttk.combobox 填充了来自数据库的数据。当用户选择数据时,我需要检索所选数据的 ID。

我有一个解决方案,但我确信有一个更优雅、更简单的解决方案,但我找不到。我用 '.' 拆分 SQL 行 ID,而不是从 Combobox 我将字符串转换为用 '.' 拆分的列表并检索 ID 的列表 [0]。

代码示例:

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

您可以 return 字典而不是来自 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

然后使用list(rows.keys())作为下拉项:

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

最后用rows[pickedString]得到ID在GetIDFromDropDown():

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