I have a list of colors which are assigned to different labels via index numbering. I have a for loop and an if statement that checks if any of the colors are black. If a color is 'black' I want the for loop to change the 'fg' attribute of that label to white. I can get the variable 'label_name' formatted correctly but I can't get it to be recognized as a label so I can change the attribute.
Note: the colors in the actual code are variables that change
Note: Its my understanding you can use hex code '#FFFFFF' or 'white' interchangeably
color_list = ['red','blue', 'green', 'black']
counter = 0
for item in color_list:
counter += 1
if item.find("black"):
label_name = "header{}".format(counter)
print(label_name)
# this line is where I can't get passed
label_name['fg'] = 'white'
header1 = Label(root, bg=color_list[0])
header2 = Label(root, bg=color_list[1])
header3 = Label(root, bg=color_list[2])
header4 = Label(root, bg=color_list[3])
header1.grid(row=1, column=0)
header2.grid(row=1, column=1)
header3.grid(row=2, column=0)
header4.grid(row=2, column=1)
I tried using .config same problem:
label_name.config(fg = 'white')
I also tried this which changes all the label text to white:
font_color = '#000000'
for item in color_list:
if item.find('#000000'):
font_color = '#FFFFFF'
else: pass
header1 = Label(root, bg=color_list[0], fg=font_color)
The first problem is that you are trying to modify the properties of a string, label_name
, which is not a tkinter widget. Even if this did work, you try to change the text colour before creating the widgets, so your for loop needs to go after you've made the widgets.
You still need a way to get a reference to the tkinter widgets to change their foreground, so you can use it to check the background as well. To get a list of children of root
, you can use root.winfo_children()
. You can then iterate through this list and use cget
to get the background colour of each widget. If it's equal to black, you can set the foreground to white with .config
(item['fg'] = 'white'
would also work).
If there are other widgets in the root window you don't want to change the foreground of, replace root.winfo_children()
with (header1, header2, header3, header4)
. Then only the headers will be affected. Here's the updated code:
color_list = ['red','blue', 'green', 'black']
header1 = Label(root, bg=color_list[0])
header2 = Label(root, bg=color_list[1])
header3 = Label(root, bg=color_list[2])
header4 = Label(root, bg=color_list[3])
for item in root.winfo_children():
if item.cget("bg") == 'black':
item.config(fg = 'white')
header1.grid(row=1, column=0)
header2.grid(row=1, column=1)
header3.grid(row=2, column=0)
header4.grid(row=2, column=1)