'How to fix : "RuntimeError: Too early to create image" error

from tkinter import *
from PIL import Image, ImageTk, ImageSequence
import time

def play_gif():
    global img
    img = Image.open("document2.gif")
    lbl = Label(root)
    lbl.place(x=150,y=50)

    for img in ImageSequence.Iterator(img):

        img = img.resize((300,300))
        img = ImageTk.PhotoImage(img)
        lbl.config(image = img)

        root.update()
        time.sleep(0.04)
    root.after(0,play_gif)

  
root = Tk()
root.geometry("600x400")
#root.configure(bg="white")
play_gif()

root.mainloop()
    

When I close the tkinter window, I am getting the above error, can somebody please help me fix it ?

I want to run gif in ttkinter window as a loading screen



Sources

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

Source: Stack Overflow

Solution Source