Python: "list index out of range"

Asked

Viewed 1,006 times

1

Issues:

  1. What makes the code snippet below? He’s making a mistake.
  2. How can I identify and correct this mistake?
verificar = self.tree.column(titulos_listbox[ix], width=None)

When running the code, displays the following error message:

Indexerror: list index out of range

If I remove all part of the code below, the program runs normally.

        for ix, val in enumerate(item):
            col_w = tkFont.Font().measure(val)
            verificar = self.tree.column(titulos_listbox[ix], width=None)
            if verificar<col_w:
                self.tree.column(titulos_listbox[ix], width=col_w)

The result will be the following image: inserir a descrição da imagem aqui

'''
Here the TreeView widget is configured as a multi-column listbox
with adjustable column width and column-header-click sorting.
'''
try:
    import Tkinter as tk
    import tkFont
    import ttk
except ImportError:  # Python 3
    import tkinter as tk
    import tkinter.font as tkFont
    import tkinter.ttk as ttk

class MultiColumnListbox(object):
    """use a ttk.TreeView as a multicolumn ListBox"""

    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        # s = "BANDO DE DADOS"
        #
        # msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
        #     padding=(10, 2, 10, 6), text=s)
        # msg.pack(fill='x')
        container = ttk.Frame()
        # container.pack(fill='both', expand=True)
        container.place(x=5, y=5, width=1170)

        # create a treeview with dual scrollbars
        self.tree = ttk.Treeview(columns=titulos_listbox, show="headings")
        vsb = ttk.Scrollbar(orient="vertical",
            command=self.tree.yview)
        hsb = ttk.Scrollbar(orient="horizontal",
            command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set,
            xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in titulos_listbox:
            self.tree.heading(col, text=col.title(),
                command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width to the header string
            self.tree.column(col,
                width=tkFont.Font().measure(col.title()))

        for item in banco_dados:
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value

            for ix, val in enumerate(item):
                col_w = tkFont.Font().measure(val)
                verificar = self.tree.column(titulos_listbox[ix], width=None)
                if verificar<col_w:
                    self.tree.column(titulos_listbox[ix], width=col_w)

def sortby(tree, col, descending):
    """sort tree contents when a column header is clicked on"""
    # grab values to sort
    data = [(tree.set(child, col), child) \
        for child in tree.get_children('')]
    # if the data to be sorted is numeric change to float
    #data =  change_numeric(data)
    # now sort the data in place
    data.sort(reverse=descending)
    for ix, item in enumerate(data):
        tree.move(item[1], '', ix)
    # switch the heading so it will sort in the opposite direction
    tree.heading(col, command=lambda col=col: sortby(tree, col, \
        int(not descending)))

# the test data ...

titulos_listbox = ['Data', 'Código', 'Item', 'Quantidade', 'Custo unitário', 'Custo total']
banco_dados = [
    ('01/01/2019', 123, 'teste1', 1, 10.0, 100.0, 'observação1'),
    ('02/01/2019', 456, 'teste2', 2, 20.0, 200.0, 'observação2'),
    ('03/01/2019', 789, 'teste3', 3, 30.0, 300.0, 'observação3')]



if __name__ == '__main__':
    root = tk.Tk()
    root.title("Multicolumn Treeview/Listbox")
    root["bg"] = "LightSteelBlue"
    root.geometry('1180x650+5+40')
    listbox = MultiColumnListbox()
    root.mainloop()

MultiColumnListbox()

1 answer

0


In the verificar = self.tree.column(titulos_listbox[ix], width=None) the program passes column by column searching which of them has width equal to nothing to, in the if next, assign the width of col_w.

[...]
if verificar<col_w:
                    self.tree.column(titulos_listbox[ix], width=col_w)

The error of index out of range very likely it is happening because you have 6 columns analyzed and there are only 5 of them declared, for example. You’re referring to something that doesn’t exist.

  • Ah. Thank you. I get it. In fact, the program checks if the text in the column is larger than the column and, being larger, it adjusts the width of the column. In fact he does this reverse check, checking whether the width "None" is smaller than "col-w", being smaller, he adjusts to "col_w".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.