Search code examples
pythonloopstkintertk-toolkitfor-in-loop

Make each button(color) from list turn background to correspondent color


I want to make each button (under the colors list) change the (overall window) background color to the one from its name when clicked. I guess that's kinda what I aimed at with this part of the code in line 16:

command=window.configure(background=c)

But it doesn't work... I'd really appreciate a little help here. Here's the full code:

import tkinter
window = tkinter.Tk()

window.title("Colors")
window.geometry('650x300')
window.configure(background="#ffffff")

#Create a list of colors
colors = ['red', 'green', 'blue', 'cyan', 'orange', 'purple', 'white', 'black']

#loops through each color to make button
for c in colors:
    #create a new button using the text & background color
    b = tkinter.Button(text=c, bg=c, font=(None, 15), command=(window.configure(background=c)))
    b.pack()

window.mainloop()

Solution

  • You need to use functools.partial to encapsulate the color value into a function (called a "closure").

    from functools import partial
    
    for c in colors:
        #create a new button using the text & background color
        b = tkinter.Button(text=c, bg=c, font=(None, 15), command=partial(window.configure, background=c))
        b.pack()