1

Im trying to create multiple buttons through a loop with TKinter, but when i run the script, 5 button-like objects get created, but only the last behaves as a button.With TKimage, im trying to overlay a picture that comes from an url inside a dictionary on each button. But the dictionary contains 5 images, and only the last button turns into an actual button, and has the final of the 5 images on it.

This is my code:

    film = films_dict['filmsoptv']["film"]                                                 #<<<< voor plaatjes films in TkinterGUI
Buttons = ['Button1','Button2','Button3','Button4','Button5']
lijstnummers = [1,2,3,4,5]
for film, i, j in zip((films_dict['filmsoptv']["film"]),(lijstnummers),(Buttons)):
    image_bytes = urlopen(film["cover"]).read()
    data_stream = io.BytesIO(image_bytes)
    pil_image = Image.open(data_stream)
    tk_image = ImageTk.PhotoImage(pil_image)
    j = Button(window,command=close,height=296,width=200,image=tk_image)
    j.grid(row=0, column=i)

films_dict contains 5 sub-dictionaries which i, by calling it in a for loop, roll through to access the sub-dictionary's cover-url. The films_dict changes every day, so i can't use passive url's.

Anyone that can help me create 5 buttons instead of one?

1 Answer 1

1

Just a guess, but I think all but the last image are garbage collected, since there is only a reference to the last image left (tk_image still points to that one after the loop). For some reason, the image being used in the Button, or in a Label does not count as a reference for the garbage collector. Try storing references to all the images in a list or dictionary, then it should work.

Also, it seems like you want to add the Button to the list Buttons by assigning it to j. This will not work, though. Better initialize Buttons as an empty list and append the new Button to that list. Try this (not tested):

images = []
buttons = []
for i, film in enumerate(films_dict['filmsoptv']["film"], 1):
    image_bytes = urlopen(film["cover"]).read()
    data_stream = io.BytesIO(image_bytes)
    pil_image = Image.open(data_stream)
    tk_image = ImageTk.PhotoImage(pil_image)
    j = Button(window, command=close, height=296, width=200, image=tk_image)
    j.grid(row=0, column=i)
    images.append(tk_image)
    buttons.append(j)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.