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

Tkinter Treeview删除数据报错:self.tk.call(self._w, "delete", items)问题求助

解决ttk.Treeview删除所有项时的self.tk.call报错问题

我一眼就看出问题所在了——你把tkinter普通Listbox的删除逻辑用到了ttk.Treeview上,这俩控件的API完全不一样!

错误原因

你在show()函数里写的listBox.delete(0, END)是针对传统Listbox的语法,但你的listBox实际上是ttk.Treeview控件,它没有0或END这种参数。Treeview的delete方法需要传入具体的项目ID,直接用0, END会触发底层Tcl/Tk的调用错误,也就是你看到的self.tk.call(self._w, "delete", items)。

修复方案

把show()函数里的删除代码替换成Treeview专用的写法:

listBox.delete(*listBox.get_children())

解释一下:

  • listBox.get_children()会返回Treeview中所有顶层项目的ID列表
  • *是Python的解包运算符,把列表里的每个ID作为单独参数传给delete方法,这样就能一次性清空所有现有项

修改后的完整show()函数如下:

def show():
    # 正确清空Treeview的方式
    listBox.delete(*listBox.get_children())
    mysqldb = mysql.connector.connect(host="localhost", user="root", password="", database="payroll")
    mycursor = mysqldb.cursor()
    mycursor.execute("SELECT id,empname,mobile,salary FROM registation")
    records = mycursor.fetchall()
    print(records)
    for i, (id, stname, course, fee) in enumerate(records, start=1):
        listBox.insert("", "end", values=(id, stname, course, fee))
    mysqldb.close()

额外优化建议

为了提升用户体验,你可以在增删改操作完成后自动刷新列表,不用用户手动点击「View Latest」:
比如在Add()、update()、delete()函数的messagebox.showinfo之后,添加一行show()调用,举个例子:

def Add():
    # 原有代码...
    messagebox.showinfo("information", "Employee inserted successfully...")
    e1.delete(0, END)
    e2.delete(0, END)
    e3.delete(0, END)
    e4.delete(0, END)
    e1.focus_set()
    show()  # 新增这行,自动刷新列表

这样用户做完增删改操作后,列表会立刻更新,不用再手动点按钮啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:18:14