Jan-06-2021, 02:15 PM
I have a random image picker, and images created by PIL are not garbage collected, even if I delete self.rand_img.image. I can collect it by destroying self.rand_img, but it's very inconvenient. It's there any other way, how to solve this?
Here's my code.
Here's my code.
import os import random from PIL import Image, ImageTk import tkinter as tk class App: def __init__(self): def load_imgs(path=str()): for i in os.listdir(self.path + path): if i.endswith((".jpg", ".jpeg", ".png")): self.pics.append(path + i) elif os.path.isdir(self.path + path + i): load_imgs(path + i + "\\") self.w = None self.h = None self.pics = [] self.path = input() + "\\" self.root = tk.Tk() self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) load_imgs() print(len(self.pics)) self.rand_img = tk.Label(self.root, bg="red") self.rand_img.grid(row=0, column=0, sticky="nwse") self.rand_img.update() self.new_img() self.btn = tk.Button(self.root, text="Next", command=self.new_img) self.root.bind("<Return>", self.new_img) self.btn.grid(row=1, column=0) self.root.mainloop() def new_img(self, event=None): def resize(event=None, img=None): w = img.size[0] h = img.size[1] self.rand_img.update() if w > h: master = w / self.rand_img.winfo_width() w = self.rand_img.winfo_width() h /= master elif h > w: master = h / self.rand_img.winfo_height() h = self.rand_img.winfo_height() w /= master if w > self.rand_img.winfo_width(): master = w / self.rand_img.winfo_width() w = self.rand_img.winfo_width() h /= master elif h > self.rand_img.winfo_height(): master = h / self.rand_img.winfo_height() h = self.rand_img.winfo_height() w /= master if self.w != w or self.h != h: img = img.resize((int(w), int(h))) img_tk = ImageTk.PhotoImage(image=img) self.rand_img.configure(image=img_tk) self.rand_img.image = img_tk print(self.rand_img.image) self.w = w self.h = h img = Image.open(self.path + self.pics[random.randint(0, len(self.pics))]) resize(img=img) self.rand_img.bind("<Configure>", lambda event: resize(event, img=img)) app = App()