How to attach a vertical scrollbar in Tkinter text widget?

TkinterPythonGUI-Programming

The Scrollbar widget in tkinter is one of the useful widgets that is used to pack the container elements and their contents with a scrollbar. With Scrollbars, we can view large sets of data very efficiently.

Generally, Tkinter allows to add vertical and horizontal scrollbar in the application. By default, the vertical scrollbars are available in the constructor and we don't need to have an orientation for the scrollbar. To attach a vertical scrollbar in a Tkinter text widget, you can use xscrollcommand and yscrollcommmand to set the value of vertical and horizontal scrollbars.

Example

# Import the required library
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

# Create an instance of tkinter frame
win=Tk()

# Set the geometry
win.geometry("700x350")

# Add a Scrollbar(horizontal)
v=Scrollbar(win, orient='vertical')
v.pack(side=RIGHT, fill='y')

# Add a text widget
text=Text(win, font=("Georgia, 24"), yscrollcommand=v.set)

# Add some text in the text widget
for i in range(10):
   text.insert(END, "Welcome to Tutorialspoint...\n\n")

# Attach the scrollbar with the text widget
v.config(command=text.yview)
text.pack()

win.mainloop()

Output

If we run the above code, it will display a text editor that will have some text in it. The text widget is packed with a vertical scrollbar and it gets executed whenever the text overflows in the text editor.

raja
Published on 05-Aug-2021 14:15:03
Advertisements