How to attach a vertical scrollbar to a Treeview using Tkinter?

Published December 30, 2021

A Treeview widget allows users to output data in both hierarchical and tabular formats. A Treeview widget has a list of items, each of which has one or more columns. The first column may include text and an icon that indicates whether it is expandable or not, while the other columns carry the values of each row.

The treeview's top row contains the headers, which are used to identify each column by name.

In this Tkinter tutorial, we'll build a Tkinter Treeview to show tabular data and add a vertical scrollbar to it.

 

How to Create a TreeView in Tkinter and Attach a Vertical Scrollbar

If you want to show a large list of items in your Tkinter TreeView, you must include a scrollbar. To add a vertical scrollbar to your TreeView, first, write a scrollbar constructor and then customize it by adding commands. Take a look at the example below to see how it works.

 

Example

In the following example, we will provide a list of English Premier League football teams and Italian football clubs.

from tkinter import *

from tkinter import ttk

win= Tk()

win.geometry("800x450")

style= ttk.Style()

style.theme_use('clam')

tree= ttk.Treeview(win, column=("c1", "c2"), show='headings', height= 8, selectmode="browse")

tree.column("#1", anchor=CENTER, stretch= NO)

tree.heading("#1", text="Premier League")

tree.column("#2", anchor=CENTER, stretch=NO)

tree.heading("#2", text="Italian Seria A")

tree.insert('', 'end', text= "1",values=('Man City', 'Juventus'))

tree.insert('', 'end', text="2",values=('Chelsea','Lazio'))

tree.insert('', 'end', text="3",values=('Man United','Bologna'))

tree.insert('', 'end', text="4",values=('Norwitch','Milan'))

tree.insert('', 'end', text="5",values=('Burnley','Roma'))

tree.insert('', 'end', text= "6",values=('Watford','Napoli'))

tree.insert('', 'end',text= "7",values=('Crystal Palace','Cagliari'))

tree.insert('', 'end',text= "8",values=('Everton','Verona'))

tree.insert('', 'end', text= "9", values=('Arsenal','Sasuollo'))

treeScroll = ttk.Scrollbar(win)

treeScroll.configure(command=tree.yview)

tree.configure(yscrollcommand=treeScroll.set)

treeScroll.pack(side= RIGHT, fill= BOTH)

tree.pack()

win.mainloop()

 

 

TKinter Vertical scrollbar

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1000 Views