Python Forum

Full Version: changing background color of a button
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a beginner to Python but not to programming in general.

I have the following code for creating 3 buttons:
for i in range(1, 3):
    aButton = "button" + str(i)
    aButton = tkinter.Button(Gui, font=Font1, text=i, image=myPixel, width=70, height=70, compound="c", bg='white', activebackground='white')
    aButton['command'] = partial(setBG, aButton)
    aButton.grid(row=1, column=i)
And it works. I get a three buttons.

Now, I want to use a function called ChangeColor to change the background color to red.
def ChangeColor():
    tkinter.button1['bg'] = 'red'
I run the script but I get
Error:
module 'tkinter' has no attribute 'button1'
How do I get a reference to any of the three buttons and change its background color?

.
The way you have it written you are just dismissing the reference to each button
Quote:
for i in range(1, 3):
    aButton = "button" + str(i)
    aButton = tkinter.Button(Gui, font=Font1, text=i, image=myPixel, width=70, height=70, compound="c", bg='white', activebackground='white')
    aButton['command'] = partial(setBG, aButton)
    aButton.grid(row=1, column=i)
You only actually obtain the last button as aButton. You need a reference to each button to be able to change each button. So either, append each button to a list to save each reference. Loop the list and change each object color in the list as you please. OR use classes and call the attribute directly to change the color.
Thanks.

I created a list of buttons as you suggested.

buttons = []
then I add each button to that list
buttons.append(aButton)
But,
buttons[i]['bg'] = 'red'
does not work.
What is the correct syntax that I need to use?

.

Answering my own question.

I did not need
aButton = "button" + str(i)
.

for i in range(1, 3):
    aButton = tkinter.Button(Gui, font=Font1, text=i, image=myPixel, width=70, height=70, compound="c", bg='white', activebackground='white')
    buttons.append(aButton)
    aButton['command'] = partial(setBG, aButton)
    aButton.grid(row=1, column=i)
and add
		buttons[i].config(background="red")