Python Forum

Full Version: change background color of button
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Starting to learn Python though I know other languages such as VB.NET

I create 5 buttons.
tkinter.Button(Gui, "1", command=callback).grid(row=0, column=1)
...

tkinter.Button(Gui, "5", command=callback).grid(row=0, column=5)
When I click on any of the 5 buttons, I want to change its background color.

I don't know how to write a generic callback function that changes the background color for only the button that was clicked.
This method uses classes
import tkinter as tk

root = tk.Tk()

class Button:
    def __init__(self, win, text, color):
        self.btn = tk.Button(win, text=text, command=self.change_color)
        self.btn.pack()
        self.color = color

    def change_color(self):
        self.btn.config(bg=self.color)

btn1 = Button(root, 'one', '#00ffff')
btn2 = Button(root, 'two', '#0000ff')

root.mainloop()
        
Hi ieee488

Here a further variant to play around with:
import tkinter as tk
 
root = tk.Tk()

def button_callback(state):
    print('Button Callback', state)
     
class Button(tk.Button):
    
    def __init__(self, parent, active_color=None, **kwargs):
        self.active_color = active_color
        super().__init__(**kwargs)
        
        self.callback = kwargs['command'] if 'command' in kwargs else None
        self['command'] = self.change_color
        self.bg_color = self['bg']
        self.state = False
        
    def change_color(self):
        self.state = not self.state
        self['bg'] = self.active_color if self.state else self.bg_color
        if self.callback: self.callback(self.state)
 
Button(root, '#00ffff', text='one', command=button_callback).pack()
Button(root, '#90ee90', text='two').pack()
Button(root, text='three').pack()
 
root.mainloop()
Tested with Ubuntu 16.04 & Python 3.5

wuf :-)
Thank you both.

I ended up with
def setBG(button):
    if button['bg'] == 'white':
        button['bg'] = 'yellow'
        button['activebackground'] = 'yellow'
    else:
        button['bg'] = 'white'
        button['activebackground'] = 'white'
where the buttons are created with
aButton = tkinter.Button(Gui, bg='white', activebackground='white')
aButton['command'] = partial(setBG, aButton)
This was something quick, though using class is definitely the better way.
I have a lot to learn with Python.

.