'How to fix Tkinter dead frezzing or crashing because of huge data?

I am trying to make a program to display one single image (.png extension) at once but giving a button to the user to change the picture.

What I have done is:

  1. Reading the Image from my directory with help of Pillow module

  2. Appended it to a list

  3. With a button I increase or decrease the index of the list.

(Note I have to read 600 images approx.)

Here's the code:

import os
from tkinter import *
from PIL import ImageTk,Image
import threading,time
#Define the tkinter instance
x=0
win= Tk()
dir_path= os.path.dirname(os.path.realpath(__file__))
print(dir_path)
l1=[]
#Define the size of the tkinter frame
win.geometry("700x400")
def start():
    threading.Thread(target=bg).start()
    win.after(5000,threading.Thread(target=fg).start())
#Define the function to start the thread
def bg():
    print("bg")
    for i in range(1,604):
        a=Image.open(f"{dir_path}\\{i}.png")
        a=a.resize((500,700), Image.ANTIALIAS)
        b=ImageTk.PhotoImage(a)
        l1.append(b)
        print(b)
        print(len(l1))
def fg():
    def add():
        global x
        x+=1
        img2=l1[x]
        d.configure(image=img2)
        d.image = img2
        d.update()
    global d
    d=Label(win,image=l1[x])
    d.pack()
    Button(win,text="add",command=add).place(x=0,y=0)
label= Label(win)
label.pack(pady=20)
#Create button
b1= Button(win,text= "Start", command=start)

b1.pack(pady=20)

win.mainloop()

But the problem is that the Tkinter gets dead freeze and laggy to an extent that the GUI is not operable.

So my question is,

How to fix Tkinter dead Frezzes and if there is any way to read the images as fast as possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source