Search code examples
pythontkinterttk

How to change the colour of scrollbar with ttk.style tkinter


I have a customised scrollbar with ttk to remove arrows, I was wondering how I can change the colour of the scrollbar. My code generates a list of buttons with names from a directory that can be scrolled through.

My code:

import tkinter as tk
from tkinter import ttk, messagebox
import os

bgCOL = "#2F3342"
sideCOL = '#4B5169'
txtCOL = '#8490BA'
btmCOL = '#575B66'
scrollCOL = '#373b4f'

yVal = 0

root = tk.Tk()

# Sets a new style for the scollbar to remove the arrows
style = ttk.Style(root)
style.layout('arrowless.Vertical.TScrollbar', [('Vertical.Scrollbar.trough', 
        {'children': [('Vertical.Scrollbar.thumb', {'expand': '1', 'sticky': 'nswe'})], 'sticky': 'ns'})])


canvas = tk.Canvas(root, width=348, height=665, bg=scrollCOL, highlightthickness=0)
scroll_y = ttk.Scrollbar(root, orient="vertical", command=canvas.yview, style='arrowless.Vertical.TScrollbar')
frame2 = tk.Frame(canvas, bg=scrollCOL)



for file in os.listdir('userSounds/data'):

    yVal = yVal + 1
    button = tk.Button(frame2, font=('Bahnschrift', 16), bd=0, highlightthickness=0, bg=sideCOL, fg='white',
        text=file.replace('.txt', ''), justify='left')   

    button.grid(row=yVal, column =0, pady=5, padx=9)
    button['width'] =27


# Puts the frame in the canvas
canvas.create_window(0, 0, anchor='nw', window=frame2)

# Makes sure everything is displayed before configuring the scrollregion
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scroll_y.set)
                
canvas.pack(side='left')
scroll_y.pack(fill='y', side='right')

root.mainloop()

Any help is GREATLY appreciated.


Solution

  • You can use style.configure() to change the color of ttk.Scrollbar, for example:

    style.configure("arrowless.Vertical.TScrollbar", troughcolor="blue") # change blue to whatever color you want
    

    However not all the themes support changing color of scrollbar, you may need to use another theme that supports it by calling style.theme_use():

    style.theme_use("alt") # "alt" theme supports changing color of scrollbar