You need to enable JavaScript to run this app. tkinter Treeview对接数据库开发时指定代码行报语法错误的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

tkinter Treeview对接数据库开发时指定代码行报语法错误的问题咨询

代码问题排查

触发语法报错的直接原因

标注#2/#3/#4的行存在两类括号错误,直接触发语法解析失败:

  • tv.set() 外层调用缺少闭合右括号
  • "#{}".format(...) 方法的括号提前闭合,把本来属于tv.set()的column、value参数错误包入format()的调用域内

改完语法后会触发的逻辑/运行时错误

  • Treeview列配置写法完全错误
    原代码将tv.column方法直接赋值为字符串:
    tv.column=("NAME")
    tv.column = ("GENDER")
    tv.column = ("COMMENTS")
    
    这种写法会直接覆盖tv.column的原生方法,后续操作会报“字符串不可调用”错误。正确的列配置需要在Treeview初始化时传入columns参数声明所有自定义列,再调用tv.column()方法配置列宽、对齐方式等属性。
  • insert方法参数结构错误
    原代码的insert调用把本该传给tv.insert()的text参数错误传入了format()方法,会触发format()不接受关键字参数的报错。
  • 缩进层级错误
    末尾self.root.mainloop()的缩进和类方法的层级不匹配,会触发缩进解析错误。

修正后的可运行代码

import tkinter as tk
from tkinter import ttk
from registration import DBConnect

class ListTicket():
    def __init__(self):
        self.db = DBConnect()
        self.root = tk.Tk()
        # 初始化时声明所有自定义列
        tv = ttk.Treeview(self.root, columns=("NAME", "GENDER", "COMMENTS"))
        tv.pack()
        # 配置默认ID列(#0)的标题与样式
        tv.heading("#0", text="ID")
        tv.column("#0", width=50, anchor="center")
        # 配置自定义列的标题
        tv.heading("NAME", text="NAME")
        tv.heading("GENDER", text="GENDER")
        tv.heading("COMMENTS", text="COMMENTS")
        # 从数据库读取数据填充表格
        cursor = self.db.Show()
        for row in cursor:
            row_id = "#{}".format(row["ID"])
            tv.insert("", "end", row_id, text=row["ID"])
            tv.set(row_id, column="NAME", value=row["name"])
            tv.set(row_id, column="GENDER", value=row["gender"])
            tv.set(row_id, column="COMMENTS", value=row["comment"])
        self.root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 21:15:10