Home > Mobile >  _tkinter.TclError: Item {...} not found
_tkinter.TclError: Item {...} not found

Time:07-16

I'm trying to build a python program that has excel features. After following this tutorial for opening a excel spreadsheet in Treeview using Tkinter, i tried to make a function to delete columns after you name it in a entry widget. But it has returned this error:

_tkinter.TclError: Item {'width': 200, 'minwidth': 20, 'stretch': 1, 'anchor': 'w', 'id': 'Sit Sin'} not found

("Sit Sin" is the name of a column in a spreadsheet i'm using)

This is the code for opening the excel file the function for deleting columns

def clear_tree():
    Ttree.delete(*Ttree.get_children())

def open_file():
    namefile= filedialog.askopenfilename(
        initialdir="C:",
        title="Open a File",
        filetype=(("xlsx files", "*.xlsx"), ("All files", "*.*"))
    )
    namefile= r"{}".format(namefile)
    df = pd.read_excel(namefile)

    # clears the treeview
    clear_tree()
    # Set up new tree
    Ttree['column'] = list(df.columns)
    Ttree['show'] = "headings"
    # loop in the column list
    for column in Ttree['column']:
        Ttree.heading(column, text=column)
    # putting data in the treeview
    df_columns = df.to_numpy().tolist()
    # loop the data and putting them on the screen
    for row in df_columns:
        Ttree.insert("", "end", values=row)

def drop_columns():
    namecolumn = entry_name_column.get()
    var = Ttree.column(namecolumn)
    Ttree.delete(var)

What I am doing wrong ? Is deleting columns only doable with Pandas or Xlwings ?

CodePudding user response:

Note that Ttree.column(namecolumn) returns a dictionary of the options of the given column name. Ttree.delete() is used to delete row, not column.

Treeview does not have function to delete a column, so you need to:

  • remove the heading from 'columns' option
  • remove the corresponding column from every row

Below is the modified drop_columns():

def drop_columns():
    namecolumn = entry_name_column.get().strip()
    columns = list(Ttree['columns'])
    try:
        # get the index of the column, exception when column cannot be found
        idx = columns.index(namecolumn)
        # remove the column heading
        columns.pop(idx)
        Ttree['columns'] = columns
        for col in columns:
            Ttree.heading(col, text=col)
        # remove the corresponding column from all rows
        for row in Ttree.get_children():
            values = list(Ttree.item(row, 'values'))
            values.pop(idx)
            Ttree.item(row, values=values)
    except ValueError as ex:
        print(ex)
  • Related