To be more specific, I need to create 45 different labels that I can control the bg color of individually based on the user input. The project is a lottery, and each correct number the user gets needs to change it’s bg color.
lbl_lotoNumberTip1 = Label(lotto, text="1", bg='green') lbl_lotoNumberTip2 = Label(lotto, text="2", bg='green') lbl_lotoNumberTip3 = Label(lotto, text="3", bg='green') lbl_lotoNumberTip4 = Label(lotto, text="4", bg='green') lbl_lotoNumberTip5 = Label(lotto, text="5", bg='green')
Is there a much shorter way to write this like putting it in a for loop ?
Advertisement
Answer
Some few corrections to my code
labels = {} # Create a dictionary for i in range(45): labels[f'lbl_lotoNumberTip{i+1}'] = Label(lotto, text=f"i+1", bg='green')
The code above will create the labels to access the labels use.
labels[lbl_lotoNumberTip1] # where 1 there can be replaced with any number in the range labels[lbl_lotoNumberTip2].text() # Example on how to access labels