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

Python Tkinter Treeview首列显示异常问题排查

问题:Tkinter Treeview 展示数据库费用信息异常

我用Python Tkinter写了一段代码,通过Treeview展示数据库里的费用信息,但显示结果有异常。代码如下:

def fee_foo():
    fee_screen = tk.Tk()
    fee_screen.title("Fee Information")
    fee_screen.geometry("500x500")
  # Execute the SELECT statement and retrieve the results
    # Execute the SELECT statement and retrieve the results
    query = "SELECT roll_no, paid, due_date, amount FROM fee"
    cursor.execute(query)
    results = cursor.fetchall()

    # Create the Treeview widget
    treeview = ttk.Treeview(fee_screen)
    treeview.pack(fill=tk.BOTH, expand=True)

    # Configure the columns of the Treeview widget
    treeview["columns"] = ("roll_no","paid", "due_date", "amount")
    treeview.column("roll_no",width=100)
    treeview.column("paid", width=100)
    treeview.column("due_date", width=100)
    treeview.column("amount", width=100)

    # Set the column headers of the Treeview widget
    treeview.heading("roll_no",text="Roll No")
    treeview.heading("paid", text="Paid")
    treeview.heading("due_date", text="Due Date")
    treeview.heading("amount", text="Amount")
    # Insert the rows into the Treeview widget
    for result in results:
        treeview.insert("", tk.END, text=result[0], values=result[1:])

我已经试过修改列和标题变量、调整treeview.insert里的元组索引,但问题还是没解决,麻烦帮忙排查代码错误。


问题排查与修复

你的代码核心问题是Treeview默认首列与自定义列重复,导致数据显示错位:

  • Treeview默认自带一个未命名的首列(text参数的内容会显示在这里),但你同时将roll_no设为自定义列,造成重复列。
  • 插入数据时,你把roll_no放到了默认首列的text参数中,剩下的三个字段对应四个自定义列,最后一个自定义列amount就会缺失数据,引发显示异常。

修复后的代码:

def fee_foo():
    fee_screen = tk.Tk()
    fee_screen.title("Fee Information")
    fee_screen.geometry("500x500")
    
    # 执行查询获取数据
    query = "SELECT roll_no, paid, due_date, amount FROM fee"
    cursor.execute(query)
    results = cursor.fetchall()

    # 创建Treeview并隐藏默认首列,只显示自定义列
    treeview = ttk.Treeview(fee_screen, show="headings")
    treeview.pack(fill=tk.BOTH, expand=True)

    # 配置自定义列
    treeview["columns"] = ("roll_no","paid", "due_date", "amount")
    treeview.column("roll_no", width=100)
    treeview.column("paid", width=100)
    treeview.column("due_date", width=100)
    treeview.column("amount", width=100)

    # 设置列标题
    treeview.heading("roll_no", text="Roll No")
    treeview.heading("paid", text="Paid")
    treeview.heading("due_date", text="Due Date")
    treeview.heading("amount", text="Amount")
    
    # 插入完整数据到自定义列
    for result in results:
        treeview.insert("", tk.END, values=result)

说明:

  1. 添加show="headings"隐藏Treeview默认首列,让所有数据通过自定义列展示。
  2. 插入数据时直接将完整的查询结果元组传给values参数,无需使用text参数,保证数据与自定义列一一对应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:05:44