Creating scrollable Listbox within a grid using Tkinter


A Listbox widget displays a list of items such as numbers list, items list, list of employees in a company, etc. There might be a case when a long list of items in a Listbox needs a way to be viewed inside the window. For this purpose, we can attach scrollbars to the Listbox widget by initializing the Scrollbar() object. If we configure and attach the Listbox with the scrollbar, it will make the Listbox scrollable.


In this example, we will create a Listbox with a list of numbers ranging from 1 to 100. The Listbox widget has an associated Scrollbar with it.

#Import the required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame

#Create an object of Scrollbar widget
s = Scrollbar()

#Create a horizontal scrollbar
scrollbar = ttk.Scrollbar(win, orient= 'vertical')
scrollbar.pack(side= RIGHT, fill= BOTH)

#Add a Listbox Widget
listbox = Listbox(win, width= 350, font= ('Helvetica 15 bold'))
listbox.pack(side= LEFT, fill= BOTH)

#Add values to the Listbox
for values in range(1,101):
   listbox.insert(END, values)

listbox.config(yscrollcommand= scrollbar.set)

#Configure the scrollbar
scrollbar.config(command= listbox.yview)



Running the above code will display a window containing a scrollable Listbox.

Published on 26-May-2021 12:13:08