Scrappy Coco
Scrappy Coco

Reputation: 116

Tkinter Treeview insert value at the last row of a specific column

I have a list of values which are processed using a web application with for loop and each gives different 5 types of result and then i append the values inside a list as per the result which i have received which i want to reflect using a Tkinter Treeview Table.

i have tried this linked answer https://stackoverflow.com/a/54208124/10401287 but each time it creates a new row at the end of the table. But i want to insert the values at the last row of that specific column.

what i get:

success |  Fail | stage1  | stage2  | stage3|
id1
id2
id3
           id4
                    id5
id6
                            id7
 id8                          
                            id9

what i want:

success |  Fail | stage1  | stage2  | stage3|
id1         id4     id5      id7
id2                          id9
id3                    
id6
id8

sample data = ['id1','id2','id3','id4','id5','id6','id7','id8','id9']
                            

I try this code to insert a list of values to specific column but it throws item not found error:

self.tree_view.insert('stage2',END, values=('id7','id9'))

Upvotes: 0

Views: 2028

Answers (1)

acw1668
acw1668

Reputation: 46669

You can use Treeview.set(...) instead of Treeview.insert(...) when you want to append data in a particular column. But you need to create the row before appending to that column.

Below is an example code:

import tkinter as tk
from tkinter import ttk
import random

root = tk.Tk()

columns = ("success", "fail", "stage1", "stage2", "stage3")
tree = ttk.Treeview(root, columns=columns, show="headings")
tree.pack()

for col in columns:
    tree.heading(col, text=col)
    tree.column(col, anchor="c", width=100)

data = ['id1','id2','id3','id4','id5','id6','id7','id8','id9']

# dictionary to store the number of items filled in each column
rowcount = {col:0 for col in columns}
treesize = 0
for item in data:
    # use random choice from columns as an example
    col = random.choice(columns)
    rowcount[col] += 1
    if rowcount[col] > treesize:
        # insert a dummy row
        tree.insert("", "end", iid=treesize, value=[])
        treesize += 1
    # append the item in corresponding column
    tree.set(rowcount[col]-1, col, item)

root.mainloop()

Upvotes: 1

Related Questions