admin管理员组文章数量:1432454
I am building an app with tkinter and running into some annoying issues.
When I load my data into the ttk treeview, I see that there are always some additional columns on the right side of my treeview which are empty. I realized for a bigger data set there are many more columns which are empty (actual data is loaded correctly). I want to get rid of these extra columns or know the source of this. I have attached a code sample below to show the issue.
I would also like to create a column selection functionality but unless the above issue is solved I don't feel like moving forward with it. Is there a simple solution to get rid of the empty columns? is column selection possible out of the box? The idea is to have a little bit excel kind of functionality but not too elaborate.
import pandas as pd import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo root = tk.Tk() root.title('Treeview demo') root.geometry('620x200') data = {'Name':['Tom', 'nick', 'krish', 'jack', 'mack', 'tack', 'crack', 'lack'], 'Age':[20, 21, 19, 18, 20, 21, 19, 18]} df = pd.DataFrame(data) tree = ttk.Treeview(root, columns=df.columns, show='headings') scrollbar_y = ttk.Scrollbar(root, command=tree.yview) scrollbar_x = ttk.Scrollbar(root, command=tree.xview, orient=tk.HORIZONTAL) tree.config(xscrollcommand=scrollbar_x.set, yscrollcommand=scrollbar_y.set) scrollbar_y.pack(fill=tk.Y, side=tk.RIGHT) scrollbar_x.pack(fill=tk.X, side=tk.BOTTOM) tree.pack(fill="both", expand=True) df.dropna(axis=1, how='all', inplace=True) df.columns = [str(x)[:50] for x in df.columns] df = df.reset_index(drop=True) print("all cols : ", df.columns) print(df.columns) # display the data in the treeview. df_list = list(df.columns) df_reset = df.to_numpy().tolist() print("No of columns ", len(df_list)) tree["columns"] = df.columns for i in range(len(df_list)): col = df_list[i] tree.column(i, anchor='c') tree.heading(i, text=col) j = 0 for dt in df_reset: v = [r for r in dt] print("v ", v) tree.insert('', 'end', iid=j, values=v) j += 1 print("Total rows : ", j) root.mainloop()
Thanks for your suggestions in advance!
Edit: fixed the typo in instantiation of treeview to df.columns as suggested. In the real code I Instantiate an empty tree and later on populate it with content and set columns using
tree["columns"] = df.columns.
I am building an app with tkinter and running into some annoying issues.
When I load my data into the ttk treeview, I see that there are always some additional columns on the right side of my treeview which are empty. I realized for a bigger data set there are many more columns which are empty (actual data is loaded correctly). I want to get rid of these extra columns or know the source of this. I have attached a code sample below to show the issue.
I would also like to create a column selection functionality but unless the above issue is solved I don't feel like moving forward with it. Is there a simple solution to get rid of the empty columns? is column selection possible out of the box? The idea is to have a little bit excel kind of functionality but not too elaborate.
import pandas as pd import tkinter as tk from tkinter import ttk from tkinter.messagebox import showinfo root = tk.Tk() root.title('Treeview demo') root.geometry('620x200') data = {'Name':['Tom', 'nick', 'krish', 'jack', 'mack', 'tack', 'crack', 'lack'], 'Age':[20, 21, 19, 18, 20, 21, 19, 18]} df = pd.DataFrame(data) tree = ttk.Treeview(root, columns=df.columns, show='headings') scrollbar_y = ttk.Scrollbar(root, command=tree.yview) scrollbar_x = ttk.Scrollbar(root, command=tree.xview, orient=tk.HORIZONTAL) tree.config(xscrollcommand=scrollbar_x.set, yscrollcommand=scrollbar_y.set) scrollbar_y.pack(fill=tk.Y, side=tk.RIGHT) scrollbar_x.pack(fill=tk.X, side=tk.BOTTOM) tree.pack(fill="both", expand=True) df.dropna(axis=1, how='all', inplace=True) df.columns = [str(x)[:50] for x in df.columns] df = df.reset_index(drop=True) print("all cols : ", df.columns) print(df.columns) # display the data in the treeview. df_list = list(df.columns) df_reset = df.to_numpy().tolist() print("No of columns ", len(df_list)) tree["columns"] = df.columns for i in range(len(df_list)): col = df_list[i] tree.column(i, anchor='c') tree.heading(i, text=col) j = 0 for dt in df_reset: v = [r for r in dt] print("v ", v) tree.insert('', 'end', iid=j, values=v) j += 1 print("Total rows : ", j) root.mainloop()
Thanks for your suggestions in advance!
Edit: fixed the typo in instantiation of treeview to df.columns as suggested. In the real code I Instantiate an empty tree and later on populate it with content and set columns using
tree["columns"] = df.columns.
Share
Improve this question
edited Nov 18, 2024 at 18:24
user3840530
asked Nov 18, 2024 at 18:13
user3840530user3840530
3022 gold badges4 silver badges14 bronze badges
0
2 Answers
Reset to default 1If you print out tree["columns"]
after tree["columns"] = df.columns
, you will get:
("Index(['Name',", "'Age'],", "dtype='object')")
So you actually configure the treeview to have three columns instead of two.
You need to convert df.columns
to list:
tree["columns"] = df.columns.to_list()
Or simply use df_list
(result of converting df.columns
to list) instead of df.columns
:
tree["columns"] = df_list
And the result of your code:
You need to use the actual column names df.columns
instead of numerical indices to configure the Treeview. This ensures proper alignment between the DataFrame columns and the Treeview, preventing the appearance of extra empty columns.
import pandas as pd
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Treeview demo')
root.geometry('620x200')
data = {'Name': ['Tom', 'Nick', 'Krish', 'Jack', 'Mack', 'Tack', 'Crack', 'Lack'],
'Age': [20, 21, 19, 18, 20, 21, 19, 18],
'City': ['NY', 'LA', 'SF', 'CHI', 'HOU', 'DAL', 'SEA', 'ATL']}
df = pd.DataFrame(data)
tree = ttk.Treeview(root, show='headings')
scrollbar_y = ttk.Scrollbar(root, command=tree.yview)
scrollbar_x = ttk.Scrollbar(root, command=tree.xview, orient=tk.HORIZONTAL)
tree.config(xscrollcommand=scrollbar_x.set, yscrollcommand=scrollbar_y.set)
scrollbar_y.pack(fill=tk.Y, side=tk.RIGHT)
scrollbar_x.pack(fill=tk.X, side=tk.BOTTOM)
tree.pack(fill="both", expand=True)
columns = list(df.columns)
tree["columns"] = columns
for col in columns:
tree.column(col, anchor='c')
tree.heading(col, text=col)
for index, row in df.iterrows():
tree.insert('', 'end', values=row.tolist())
def toggle_column(col):
if tree.heading(col, option="text") == "":
tree.heading(col, text=col)
tree.column(col, width=100)
else:
tree.heading(col, text="")
tree.column(col, width=0)
menu = tk.Menu(root)
root.config(menu=menu)
columns_menu = tk.Menu(menu, tearoff=0)
menu.add_cascade(label="Columns", menu=columns_menu)
for col in columns:
columns_menu.add_command(label=col, command=lambda c=col: toggle_column(c))
root.mainloop()
本文标签: pythonHow to make the ttk treeview not show extra empty columnsStack Overflow
版权声明:本文标题:python - How to make the ttk treeview not show extra empty columns? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745602412a2665645.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论