How to Add a Column to a Tkinter TreeView Widget?
Tkinter is a widely used Python library for creating GUI (Graphical User Interface) applications. It contains numerous widgets, including the Treeview widget, which allows you to create a hierarchical display of items, similar to a file manager or directory tree.
The Tkinter Treeview widget has two types of columns: the “tree column,” which is the first column and contains the tree structure of the widget, and other columns that contain additional information. In this article, you’ll learn how to add a new column to a Tkinter Treeview widget using simple and understandable Python code.
Steps to Add a New Column
Follow these simple steps to add a new column to a Tkinter Treeview widget:
- Import the necessary modules:
from tkinter import *
from tkinter.ttk import *
- Create a new instance of the Treeview widget and specify its columns:
tree = Treeview(root, columns=('Name', 'Age', 'Gender'))
Here, root
is the root window object, and Name
, Age
and Gender
are the column headings you want to include.
- Add data to the columns:
tree.insert('', '0', values=('John', 25, 'Male'))
tree.insert('', '1', values=('Jane', 30, 'Female'))
Here, insert()
method is used to add the data to the tree. The first argument ''
denotes that the data will be added to the root of the tree. The second argument 0
denotes the position of the item within that level. Finally, values
is a tuple containing the data to be added to each column.
- Add a new column:
tree['columns'] += ('Salary',)
tree.column('#3', anchor=CENTER)
tree.heading('Salary', text='Salary')
Here, +=
is used to add a new column named Salary
to the tree. The column()
method is used to adjust the width and alignment of the new column. Finally, the heading()
method is used to add a header or title for the new column.
- Add data to the new column:
tree.set('0', '#3', '5000')
tree.set('1', '#3', '8000')
The set()
method is used to add the data to the new column. Here, the first argument '0'
and '1'
are the item IDs and #3
represents the new column added in the previous step.
- Display the tree:
tree.pack()
The pack()
method is used to display the tree on the screen.
Conclusion
In this tutorial, you have learned how to add a new column to a Tkinter Treeview widget using simple Python code. You can customize the Treeview widget as per your requirements by adding new columns and adjusting the width and alignment of the columns. This widget is an essential tool for creating hierarchical data structure displays in GUI applications.