How to speed up scrolling responsiveness when displaying lots of text in Tkinter?

PythonTkinterGUI-Programming

Tkinter can also be used to render the text file and load it on the canvas. Further, the text files can be used for other purposes like manipulating the data, grabbing the data, and rendering the data for other uses.

Let us suppose that we have to read a text in the tkinter canvas file which contains more than 10,000 lines of queries in it. It would take a long time to search for a particular query in the canvas after loading the text file. To handle such large text files, we can speed up the responsiveness of the file by adding the Y scrollbar in it. We will create the side controller widget using Scrollbar Widget.

First, we will open and read the file using the “open” method and then, we will add a scrollbar in the Y-axis of the tkinter frame. To add the scrollbar in the frame, we can have an instance of it using the Scrollbar widget. It takes the window instance as the parameter and defines the other property of Scrollbar(side of the scrollbar, Axis).

Example

#Importing the tkinter library in the notebook

from tkinter import *
#Create an instance of the tkinter frame
win = Tk()
win.geometry(“700x300”)

#Create instance of Scrollbar object and define the property of the scrollbar
scrollbar = Scrollbar(win)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(win, height=300, width=100)
listbox.pack()

#Open and read the file using open method
file = open('file.txt', 'r').readlines()

for i in file:
   listbox.insert(END, i)

#Define the property of the widget
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

#display the canvas until the END button is not pressed.
mainloop()

Output

Running the above code snippet will open the canvas with a scrollbar on its side.

raja
Published on 06-Mar-2021 08:41:04
Advertisements