How do i display data from a dataframe in tkinter treeview?

I’m using the following code to display data from a pandas dataframe in a tkinter treeview:

import pandas as pd
from tkinter import ttk

mywin=Tk()
mywin.geometry('300x300')

df=pd.read_csv('<filepath of csv file>')
df_list=list(df.columns.values)
df_rset=df.to_numpy().tolist()
df_tree=ttk.Treeview(mywin,columns=df_list).pack()
                                     
for i in df_list:
    df_tree.column(i,width=100,anchor='c')
    df_tree.heading(i,text=i)
for dt in df_rset:
    v=[r for r in dt]
    df_tree.insert('','end',iid=v[0], values=v)

mywin.mainloop()

But this give me an error

AttributeError: 'NoneType' object has no attribute 'column'

How to fix this?

>Solution :

It looks like the error is being caused by the fact that you are calling the pack method on the df_tree object immediately after creating it.

The pack method arranges the widget in the parent widget and returns None. Therefore, df_tree becomes None and you are trying to call the column method on None, which causes the AttributeError to be raised.

To fix this, you can separate the creation of the df_tree widget and the call to the pack method. You can try modifying your code as follows:

df_tree = ttk.Treeview(mywin, columns=df_list)`
df_tree.pack()

This should allow you to create the df_tree widget and call the column and heading methods on it successfully.

Leave a Reply