简体   繁体   中英

Python: How can I fetch data from SQL for a ttk combobox based on the selection of another combobox

I am trying to have two ttk comboboxes that fetch data from a sqlite database. I managed to be able and list items in one combobox named divisiondropmenu using the combo_division() function. Now I am trying to do a similar thing for the second combobox named productdropmenu, but the list would need to be narrowed down based on the first selected item in combobox named divisiondropmenu.

For the SQL query to pass the needed information for the second combobox I was thinking of something of this sort:

'SELECT * FROM productname WHERE divisionname=?', (function_name())

Code for the two comboboxes so far:

from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import sqlite3


def combo_division():
    conn = sqlite3.connect('anglingdatabase.db')
    cursor = conn.cursor()
    cursor.execute('SELECT divisionname FROM productdivision')
    data = []
    for row in cursor.fetchall():
    data.append(row[0])
    return data

root = Tk()
root.title("Random Window Title")
root.geometry('1280x720')

rows = 0
while rows < 50:
    root.rowconfigure(rows, weight=1)
    root.columnconfigure(rows, weight=1)
    rows += 1


divisiondropmenu = ttk.Combobox(root)
divisiondropmenu['values'] = combo_division()
divisiondropmenu.bind('<<ComboboxSelected>>', selecteddivision)
divisiondropmenu.grid(row=1, column=2, sticky='NESW')

productdropmenu = ttk.Combobox(root)
productdropmenu['values'] = combo_product()
productdropmenu.grid(row=2, column=2, sticky='NESW')

root.mainloop()
data = combo_division()
example_sql = ''' SELECT * FROM tablename WHERE division in ('{}') '''.format("','".join(data))

You could build the actual SQL dynamically provided that the data was never user input (to avoid SQL injection).

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