0

I'm not entirely sure how to describe my issue, so heres an example:
I have a choice_id variable which takes an integer value 1 to 4
and 4 tkinter button elements: choice1, choice2, etc...
I want to be able to configure each button to have a different colour depending on which button has been clicked. I currently have a not very elegant solution:

if choice_id == 1:
    self.choice1.configure(bg="red")
if choice_id == 2:
    self.choice2.configure(bg="red")
if choice_id == 3:
    self.choice3.configure(bg="red")
if choice_id == 4:
    self.choice4.configure(bg="red")

is there a better way to do this?
I was thinking something like

[f"self.choice{choice_id}"].configure(bg="red")

where I woud be able to configure a certain button element that is dependent on the value of an integer

Any help would be greatly appreciated
thanks

Masha
  • 19
  • 3
  • 6
    Maybe you should just have a list: `self.choices`. Then you can index into it: `self.choices[0]`, `self.choices[1]`. etc.. – Mark Dec 29 '21 at 21:16
  • 4
    Dynamic variable name is not a good idea in general. Use dict or list; usually people use dict, but in this case you have a clear integer-based structure, so list would be better. – j1-lee Dec 29 '21 at 21:17
  • If you include the code that creates `self.choice1` etc it would be very easy to demonstrate how to do it with a list! Both the button creation and this configuration can be greatly simplified. – Samwise Dec 29 '21 at 21:19
  • thank you for your comments. I have decided to index into the list as @mark suggested. For some reason I didn't think of that. This question is now closed, although I feel the linked duplicate question does not provide the same answer. Just leaving this hear incase anyone else has the same issue and cant find the answer in that "duplicate" thread – Masha Dec 29 '21 at 21:23

0 Answers0