Reputation: 339
I am messing around a bit with tkinter in python. I am using images for my buttons and want to load them. There's a lot of buttons in my gui, so i thought maybe there's a way to load them and store them in variable generated inside a for loop.
This is my code:
list1 = ['apple', 'peach', 'orange']
path = 'GUI/Buttons'
def initButtons(partlist : list, path : str):
buttonsToLoad = ['ButtonActive1.png', 'ButtonInactive1.png', 'ButtonClicked1.png']
for x in partlist:
button + [str(x)] + '0' = Image.open(f'{path}/{x}/{buttonsToLoad[0]}')
button + [str(x)] + '1' = Image.open(f'{path}/{x}/{buttonsToLoad[1]}')
button + [str(x)] + '2' = Image.open(f'{path}/{x}/{buttonsToLoad[2]}')
initButtons(list1, path)
But this doesn't work! I'm a beginner to python, so maybe there's a much simpler way that I don't know! It's a weird question, i know, but i hope someone understands and can probably help me out!
Thanks in advance!
Upvotes: 1
Views: 662
Reputation: 2106
You can not name a different variable at each loop iteration, but you can store them in a dict {}
:
button = {}
def initButtons(partlist : list, path : str):
buttonsToLoad = ['ButtonActive1.png', 'ButtonInactive1.png', 'ButtonClicked1.png']
for x in partlist:
button[str(x) + '0'] = Image.open(f'{path}/{x}/{buttonsToLoad[0]}')
button[str(x) + '1'] = Image.open(f'{path}/{x}/{buttonsToLoad[1]}')
button[str(x) + '2'] = Image.open(f'{path}/{x}/{buttonsToLoad[2]}')
Then you can access your Image simply by searching its name in the dict's keys:
image = button['apple0'] # if its name is 'apple' + '0'
Upvotes: 1