0

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.

MattFunke
  • 33
  • 5

1 Answers1

1

Why is it necessary to declare a root window in order to create an image?

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.

Is there a way around this

No. You have to create a root window before you can create images using tkinter.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thank you for your insight. I gather, then, that it's not possible to perform that initialization without creating a root window. That's too bad; I think that means that I'll have to come up with ways to modify that root window after information is read in. – MattFunke Aug 11 '21 at 17:54
  • @MattFunke: _"I'll have to come up with ways to modify that root window after information is read in."_ - that shouldn't be difficult. You don't have to do any special to update the window after it has been created. – Bryan Oakley Aug 11 '21 at 19:19