Skitzafreak
Skitzafreak

Reputation: 1917

Dynamically update Tkinter Button Colour

I am currently trying to have my program change the colour of a Tkinter button.

I have the buttons stored in a list, and when the update method for the buttons is called, it is suppose to reset all the buttons, and then set the value of the passed button to green. Here is some code that works as an example of what I am trying to do:

import tkinter as tk
from tkinter import ttk

def updateButton(value):
    for btn in btnList:
        btnList[btn].configure(bg = "white")
    btnList[value].configure(bg = "green")

root = tk.Tk()

btn1 = ttk.Button(root, text = "BTN 1", command = lambda: updateButton("BTN 1"))
btn1.pack()
btn2 = ttk.Button(root, text = "BTN 2", command = lambda: updateButton("BTN 2"))
btn2.pack()

btnList = { "BTN 1" : btn1, "BTN 2" : btn2 }

root.mainloop()

The problem I am having is that when I attempt to run the updateButton method, I get the following error:

_tkinter.TclError: unknown option "-bg"

I have tried changing bg to background and still get the same error. What is wrong with my code?

Upvotes: 0

Views: 1349

Answers (1)

j_4321
j_4321

Reputation: 16169

As Bryan Oakley said, ttk buttons don't have a background option, the only way to change their background is to use a style:

import tkinter as tk
from tkinter import ttk

def updateButton(value):
    for btn in btnList:
        btnList[btn].configure(style='white.TButton')
    btnList[value].configure(style='green.TButton')

root = tk.Tk()

style = ttk.Style(root)
style.configure('white.TButton', background='white')
style.configure('green.TButton', background='green')

btn1 = ttk.Button(root, text="BTN 1", command=lambda: updateButton("BTN 1"), 
                  style='white.TButton')
btn1.pack()
btn2 = ttk.Button(root, text="BTN 2", command=lambda: updateButton("BTN 2"), 
                  style='white.TButton')
btn2.pack()

btnList = { "BTN 1" : btn1, "BTN 2" : btn2 }

root.mainloop()

Or, as the OP suggested, just switch to tk buttons that have a background option.

Upvotes: 1

Related Questions