I'm trying to create a small class to represent vital information about various GIFs that I want the software to handle. Here's my code:
from PIL import Image
import tkinter as tk
class ListifiedGif:
"""Class containing list of frames and number of frames from GIF."""
def __init__(self, filename):
gif = Image.open(filename)
self.frame_count = gif.n_frames
self.frame_list = [tk.PhotoImage(file = filename,
format = f'gif -index {i}')
for i in range(gif.n_frames)]
When I insert the following at the end of the file, I get an error.
testimg = ListifiedGif('E:\\Development\\desktop\\img\\walking_negative.gif')
print(testimg.frame_count)
print(testimg.frame_list)
... and here's the error:
Traceback (most recent call last):
File "<module1>", line 13, in <module>
File "<module1>", line 9, in __init__
File "<module1>", line 9, in <listcomp>
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 4064, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 3997, in __init__
master = _get_default_root('create image')
File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 297, in _get_default_root
raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root window
Why is it necessary to declare a root window in order to create an image? Is there a way around this so that I can simply return the list of frames (as a series of PhotoImages from tkinter) without having to worry about precisely what the window that the image will be used in looks like?
Thanks in advance for your time.
Because the underlying tcl/tk interpreter needs to be initialized before you can create images, and it is the creation of the root window that does the initialization.
No. You have to create a root window before you can create images using tkinter.