Here is a very simple example on how to do so, by making a list of all the 25 color and then using the conventional matrix looping and assigning items to the buttons, like:
from tkinter import *
root = Tk()
colors = ['Red','Orange','Yellow','Green','Blue','Purple','Brown','Magenta',
'Tan','Cyan','Olive','Maroon','Navy','Aquamarine','Turquoise','Silver',
'Lime','Teal','Indigo','Violet','Pink','Black','White','Gray','crimson']
colors = list(reversed(colors)) # Reversing list bc pop returns last item
def color_changer(btn,color):
btn.config(fg=color) # Change the color of the corresponding button
for i in range(5): # Number of rows
for j in range(5): # Number of column
color = colors.pop() # First color
btn = Button(root,text=color,fg='black',width=25)
btn.grid(row=i,column=j) # Place the widget
btn['command'] = lambda btn=btn,color=color: color_changer(btn,color) # Assign a command
root.mainloop()
There is a caveat here, you should define exactly 25 colors, else, you should use try
to catch the IndexError
that comes up and ignore it.
How does the function work?:
You are using lambda
to create a new nameless function that takes in btn
and color
and passes that btn
and color
to the color_changer()
. This way we can store corresponding btn
and color
, unlike if you would normally assign it like lambda: color_changer(btn,color)
, it is just going to pass the last popped item. This is usually how we assign commands for buttons inside a loop.
Alternative(to lambda
):
You can also use a nested function(avoiding lambdas
). So the function would be like:
def nester(btn,color):
def color_changer():
btn.config(fg=color)
return color_changer
and the command would be like:
btn['command'] = nester(btn,color)
This is similar to what functools.partial
does.