基于用户输入实现零售管理系统Combobox联动更新
解决Tkinter Combobox联动更新问题
原代码核心问题
- 联动逻辑仅在Combobox初始化时执行一次,未绑定用户选择事件,无法响应后续操作
- 控件变量作用域受限,回调函数无法访问dropdown内定义的Combobox
- 数据库操作后未关闭连接,存在资源泄漏
- 主窗口的
invoice为局部变量,dropdown直接引用会导致报错
修正后的完整代码
import tkinter as tk from tkinter import ttk import sqlite3 def main_window(): invoice = tk.Toplevel() # 绑定图片到窗口对象,避免被垃圾回收 invoice.billimage1 = tk.PhotoImage(file="C:/Users/.../Documents/CODE/billimage.PNG") label2 = tk.Label(invoice, image=invoice.billimage1) label2.pack(fill="both", expand=True) return invoice def dropdown(invoice): global combobox1, combobox2, combobox3 conn = sqlite3.connect('store.db') c = conn.cursor() # 初始化品类选项 c.execute("SELECT DISTINCT product_cat FROM raw_inventory") cat_list = [item[0] for item in c.fetchall()] # 初始化下拉框,子品类/产品初始为空 combobox1 = ttk.Combobox(invoice, values=cat_list, width=60, font=('Arial', 14)) combobox1.place(relx=0.035, rely=0.42) combobox2 = ttk.Combobox(invoice, values=[], width=60, font=('Arial', 14)) combobox2.place(relx=0.035, rely=0.49) combobox3 = ttk.Combobox(invoice, values=[], width=60, font=('Arial', 14)) combobox3.place(relx=0.035, rely=0.56) combobox4 = ttk.Combobox(invoice, values=[], width=60, font=('Arial', 14)) combobox4.place(relx=0.035, rely=0.64) # 绑定选择事件 combobox1.bind("<<ComboboxSelected>>", update_subcat) combobox2.bind("<<ComboboxSelected>>", update_product) conn.close() def update_subcat(event): selected_cat = combobox1.get() if not selected_cat: combobox2.configure(values=[]) combobox3.configure(values=[]) return conn = sqlite3.connect('store.db') c = conn.cursor() c.execute("SELECT DISTINCT product_subcat FROM raw_inventory WHERE product_cat=?", (selected_cat,)) subcat_list = [item[0] for item in c.fetchall()] combobox2.configure(values=subcat_list) combobox3.configure(values=[]) # 清空产品选项 conn.close() def update_product(event): selected_cat = combobox1.get() selected_subcat = combobox2.get() if not selected_cat or not selected_subcat: combobox3.configure(values=[]) return conn = sqlite3.connect('store.db') c = conn.cursor() c.execute("SELECT product_name FROM raw_inventory WHERE product_cat=? AND product_subcat=?", (selected_cat, selected_subcat)) product_list = [item[0] for item in c.fetchall()] combobox3.configure(values=product_list) conn.close() # 启动程序 root = tk.Tk() root.withdraw() # 隐藏默认主窗口 invoice_win = main_window() dropdown(invoice_win) root.mainloop()
关键改动说明
- 事件绑定:通过
<<ComboboxSelected>>事件,让用户选择时自动触发联动更新 - 变量作用域:将Combobox设为全局变量,确保回调函数能访问并修改其选项
- 动态查询:子品类和产品下拉框初始为空,仅在用户选择后从数据库查询对应数据,提升性能
- 资源管理:每次数据库操作后关闭连接,避免资源泄漏
- 图片引用修复:将图片绑定到窗口对象,防止被垃圾回收导致图片不显示
内容的提问来源于stack exchange,提问作者user21489407
相关产品推荐
相关产品推荐

