Changing the appearance of a Scrollbar in Tkinter (using ttk styles)

TkinterPythonGUI-Programming

Scrollbars are used to wrap an amount of text or characters in a frame or window. It provides a text widget to contain as many characters as the user wants.

The Scrollbar can be of two types: Horizontal Scrollbar and Vertical Scrollbar.

The length of a scrollbar changes whenever the number of characters in the Text widget increases. We can configure the style of Scrollbar by using ttk.Scrollbar. Ttk provides many inbuilt features and attributes that can be used to configure the Scrollbar.

Example

In this example, we will add a vertical scrollbar in a Text widget. We will use a ttk style theme to customize the look of the scrollbar. We have used here the 'classic' theme. Refer this link for a complete list ttk themes.

# 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
win.geometry("700x250")

style=ttk.Style()
style.theme_use('classic')
style.configure("Vertical.TScrollbar", background="green", bordercolor="red", arrowcolor="white")

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

# Add a Text Widget
text = Text(win, width=15, height=15, wrap=CHAR,
yscrollcommand=scrollbar.set)

for i in range(1000):
   text.insert(END, i)

text.pack(side=TOP, fill=X)

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

win.mainloop()

Output

Running the above code will display a window with a text widget and a customized vertical Scrollbar.

raja
Published on 25-May-2021 09:38:31
Advertisements