I want to create a for loop such that during each iteration of it, a new variable is created. I then want to be able to run commands on the new variable within that for loop so that I can form tkinter Buttons out of the new variables.
Example,
for i in range(0,17):
#Should create variables Button1, Button2, Button3 and so on.
Button+str(i)=tk.Button(root, image=img, command=lambda: changebg(i))
Button+str(i).grid(column=0, row=0)
The reason I want to do this is I want to put 16 images into a tkinter frame and want each button to be mapped to a different image such that when the button is clicked the root window background is set as the image of the button clicked. Earlier, I created a for loop that created 16 buttons but each button was stored in the variable “Button” and hence the command to them was modified each time. Atleast I think it was because any button I clicked changed the background to the last image created. I’ve scrapped that code now. If you want it for reference here it is,
for imgphoto in (imagedict.keys()):
imgbtnphoto=Image.open(imgphoto)
imgbtnphoto.thumbnail((120,120))
buttonphoto= ImageTk.PhotoImage(imgbtnphoto)
GridColumn=imagedict[imgphoto]%4
GridRow=imagedict[imgphoto]/4
Button= tk.Button(root, image=buttonphoto, command=lambda: changebg(str(GridColumn)+str(GridRow)))
Button.grid(column=GridColumn, row=GridRow)
Button.image=buttonphoto
At the moment, my new code has become too complicated for me to post just a part of it as an example and not have a huge chunk of my source code exposed to the internet. So if anybody doesn’t understand my query please ask me to explain further. Also if there is an alternate way to do this other than the way I specified I would gladly entertain that suggestion.
Thanks :)