简体   繁体   中英

Too early to create image - Ezgraphics

I'm trying to follow Cay Horstmann's book 'Python for Everyone'. when I try to use the ezgraphics module, I get an error saying "Too Early To Create Image".

The code I enter is:

6
7 filename = input("bliss.png")
8
9 # Load the original image.
10 origImage = GraphicsImage(filename)
11
12 # Create an empty image that will contain the new flipped image.
13 width = origImage.width()
14 height = origImage.height()
15 newImage = GraphicsImage(width, height)
16
17 # Iterate over the image and copy the pixels to the new image to
18 # produce the flipped image.
19 newRow = height - 1
20 for row in range(height) :
21 for col in range(width) :
22 newCol = col
23 pixel = origImage.getPixel(row, col)
24 newImage.setPixel(newRow, newCol, pixel)
25 newRow = newRow - 1
26 #Save the new image with a new name.
28 newImage.save("flipped-" + filename)

Any help would be appreciated

This happens when a tkinter Image* is instantiated,
(*or one of its subclasses: PhotoImage, BitmapImage)
before a Tk root has been created:

import tkinter as tk
#tk.PhotoImage()  # RuntimeError: Too early to create image
tk.Tk()
tk.PhotoImage()  # Ok

From /usr/lib/python3.6/tkinter/__init__.py :

class Image:
    ...
    def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
        ...
        if not master:
            master = _default_root
            if not master:
                raise RuntimeError('Too early to create image')

This behaviour for Image,
differs from the behaviour for other widgets.
There, if there is no default root, one will be created:

class BaseWidget(Misc):
    ...
    def _setup(self, master, cnf):
        ...
        if _support_default_root:
            global _default_root
            if not master:
                if not _default_root:
                    _default_root = Tk()
                master = _default_root

So this works (but is probably not recommended):

import tkinter as tk
tk.Label()  # Ok? An implicit global root will be created.  
tk.Tk()  # Ok? A different root, than the one used above.  

Don't know if this is intentional or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM