0

the proplem is everytime i add the photo to the button ,all the buttons turn white and last one works good with the last picutre this propgram loops throught 9 photos and put them into a button after editing it into 200x280 size here is the code of the program

from tkinter import *
from PIL import Image, ImageTk
shelf = Tk()
shelf.title("shelf")
shelf.configure(bg="#00dbff")
left_scroll = Button(shelf,text="<",font=("Arial", 16),height=7*4,width=4).grid(row = 0,rowspan=4,column=0,padx=10,pady=10)
right_scroll = Button(shelf,text=">",font=("Arial", 16),height=7*4,width=4).grid(row = 0 ,rowspan=4,column=4,padx=10,pady=10)
i = 1
j = 1
book_counter = 1
while(j<4):
    image_book = Image.open("F:\\Libary\\books image\\{number}.jpg".format(number = book_counter))
    image_book = image_book.resize((200,280))
    s = 'F:\\Libary\\books image\\{number}Edit.jpg'.format(number = book_counter)
    image_book.save(s)
    book1 =ImageTk.PhotoImage(file =s)
    Button(shelf,image=book1,borderwidth=0).grid(row = j,column=i,padx=10,pady=15)
    i+=1
    book_counter += 1
    if(i == 4):
        j+=1
        i=1

shelf.mainloop()

i tried removing the variables and the part where it change the size and saving it amd used the saved file did't work tried to but Imagetk.photoImage(file = s) in the image = in button didnt work

  • nope i am not using it in a function nor in a class – Youssef Salah Zakaria Nov 03 '22 at 12:57
  • well it is basically the same. You enter an indented block and at the end of that block the garbage collector collects everything with a refcount of 0. It doesn't matter if it is a function, method, class, while-/for-loop or a context manager with an anonymous block of code. You need to safe a reference somewhere as proposed in the linked question. If it doesn't work out for you, let me know. – Thingamabobs Nov 03 '22 at 13:02
  • ohh dam it worked all i did was add a label and put the image in the label and it worked as it said in the comments thanks for the help – Youssef Salah Zakaria Nov 03 '22 at 13:08
  • I have added an [answer](https://stackoverflow.com/a/74303954/13629335) to the linked question if you are interested. – Thingamabobs Nov 03 '22 at 13:41

0 Answers0