You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关系型数据库外键关联下Python实现锦标赛与轮次combobox联动问题求助

问题修复方案

你的代码核心错误有3处:

  1. 取值不匹配:combo_tournament.get()拿到的是锦标赛的中文/英文名称,但是All_Rounds表的tournament字段存的是锦标赛的数字ID,直接拿名称去匹配ID当然查不到结果
  2. SQL查询逻辑错误:轮次查询的SQL写死了固定ID,还重复执行三次,每次执行都会覆盖上一次的查询结果,而且SQL语句的括号、参数都没有正确匹配
  3. 初始化逻辑错误:轮次下拉框的初始值错误赋值为锦标赛名称列表,和轮次的预期内容完全不符

你可以直接替换问题区域的代码为以下修复后的版本:

# 以下为修复后的轮次下拉框代码
# COMBOBOX ROUND
lbl_rounds = Label(root, text="rounds", font=("Calibri", 11), bg="#a8dd71", fg="white")
lbl_rounds.place(x=600, y=60)
# 注意:如果你没有提前定义rounds = StringVar(),请删掉textvariable=rounds参数避免报错
combo_rounds = ttk.Combobox(root, font=("Calibri", 11), width=30, state="readonly")
combo_rounds.place(x=680, y=60)
combo_rounds.set("Select rounds")

def combo_roundsss(event=None):
    # 拿到选中的锦标赛名称
    selected_tournament_name = combo_tournament.get()
    # 未选中有效锦标赛时清空轮次选项
    if selected_tournament_name == "Select":
        combo_rounds['value'] = []
        combo_rounds.set("Select rounds")
        return
    # 第一步:根据锦标赛名称查询对应的锦标赛ID
    cursor.execute('SELECT ID_tournament FROM All_tournament WHERE tournament_name = ?', (selected_tournament_name,))
    tournament_id = cursor.fetchone()
    if not tournament_id:
        combo_rounds['value'] = []
        combo_rounds.set("无对应轮次")
        return
    tournament_id = tournament_id[0]
    # 第二步:用锦标赛ID查询对应所有轮次,按升序排序
    cursor.execute('SELECT rounds FROM All_Rounds WHERE tournament = ? ORDER BY rounds ASC', (tournament_id,))
    result = [row[0] for row in cursor]
    combo_rounds['value'] = result
    if result:
        combo_rounds.current(0)
    else:
        combo_rounds.set("无对应轮次")
    return result

# 初始化轮次下拉框为空,不要用锦标赛列表赋值
combo_rounds['value'] = []
# 绑定锦标赛选中事件
combo_tournament.bind('<<ComboboxSelected>>', combo_roundsss)

额外检查提示

你现在正常运行的团队联动函数combo_teamssss里存在隐藏问题,SQL语句的条件写的是c.teams = ?,但c对应的是All_tournament锦标赛表,这个表应该没有teams字段,建议修改为c.tournament_name = ?,避免后续出现数据匹配错误。

内容的提问来源于stack exchange,提问作者William50694

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:27:04