Skip to content
Advertisement

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?

Advertisement

Answer

The freezes of Tkinter depends on reading speed of the interpreter, because:

  • continuously reading and Showing the pictures are a huge job for Python.
  • reading images using opencv or any other image processing module wont help as reading part can become faster, but showing the image in tkinter is done using python only, so rapid changes in Label will cause tkinter to crash.

Solution:

  • Switch to a different compiler based language for example c++.
  • this solution is specifically for a image slideshow,

The solution is to use selenium with python. You can specify the image location in driver.get(image_path) and it will open the image for you, and if you want to change the image with a button, then just rename all your images with the numbers and make a button to add +1 to the index.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement