How to change the color of ttk button in Tkinter?

TkinterServer Side ProgrammingProgramming

Tkinter widgets have a consistent look and style across all the platforms and operating systems. Ttk works like CSS in an HTML script. It has many inbuilt functions, modules and methods that add style to a regular tkinter widget. Tkinter ttk buttons generally have a default color scheme, thus we can change the background color of these buttons by configuration method.


In this example, we will create a button which when pressed will change its style.

#Import the necessary library
import itertools
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter window
win = Tk()
#Set the geometry of tkinter window
#Define the style
style_1 = {'fg': 'black', 'bg': 'RoyalBlue3', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_2 = {'fg': 'white', 'bg': 'OliveDrab2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_3 = {'fg': 'black', 'bg': 'purple1', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_4 = {'fg': 'white', 'bg': 'coral2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_cycle = itertools.cycle([style_1, style_2, style_3, style_4 ])
#Define a function to update the button style
def update_style():
style = next(style_cycle)
#Create a tk button
button = Button(win,width=40,font=('Helvetica 18 bold'), text="Change
Style", command=update_style)
button.pack(padx=50, pady=50)


Running the above code will display a window with a button. When you click the button, it will switch the style of background color and text color.

Now, click the button to change the color of the Button.

Published on 15-Apr-2021 14:07:56