Home > Net >  Contents of a Tkinter table unable to be deleted
Contents of a Tkinter table unable to be deleted

Time:04-07

I'm currently trying to display a table in tkinter that refreshed every time the user switches frames. The way that I am doing this is through deleting all the contents of the table when the user switches to another frame and having the contents be added and displayed again as soon as the user views the frame with the table again.

The tree being used is

 def View():
        for row in db_actions.GetAllStudents(): #Method from a database used
            tree.insert("", tk.END, values=row)

    style = ttk.Style()
    style.configure("Treeview.Heading", font = (None, 8))
    style.configure("Treeview", font = (None, 8), rowheight=40)


    tree = ttk.Treeview(StudentView, column=("c1", "c2", "c3", "c4"),
                        show='headings', height=180)

    sidebar = ttk.Scrollbar(StudentView, orient="vertical")
    sidebar.pack(side="right", fill=tk.Y)

    sidebar.config(command=tree.yview)


    tree.column("#1", anchor='center')

    tree.heading("#1", text="First Name")

    tree.column("#2", anchor='center')

    tree.heading("#2", text="Surname")

    tree.column("#3", anchor='center')

    tree.heading("#3", text="Student Number")

    tree.column("#4", anchor='center')

    tree.heading("#4", text="Class")

    tree.pack()

    View()

The subroutine that deletes the data when switching frames

    def SwitchToMenu():
        tree.delete(tree.get_children())
        SwitchFrames(StudentView, MainMenu)

The error message recieved

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\alysw\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\alysw\OneDrive - St Anne's Catholic School\NEA stuff\Computing\attempts\Main 2.py", line 445, in SwitchToMenu
    tree.delete(tree.get_children())
  File "C:\Users\alysw\AppData\Local\Programs\Python\Python39\lib\tkinter\ttk.py", line 1246, in delete
    self.tk.call(self._w, "delete", items)
_tkinter.TclError: Item I001 I002 not found

CodePudding user response:

tree.delete handles one item at a time. You need:

    for item in tree.get_children():
        tree.delete(item)
  • Related