1

So I'm trying to draw an image to a tkinter canvas in python, and keep getting the error in the title. I have a reference to tkinter.Tk(), I've set it as the canvas's master, I've packed the canvas, and run the mainloop. This all happens upon program start. Then, I call gui.drawentity() in main.py, which attempts to create an image and draw it to the canvas.

gui.py

root = tk.Tk()
canvas = tk.Canvas(root, bg="green")

canvas.pack(fill=tk.BOTH, expand=True)
root.mainloop()

def drawentity(entity):
    imgPath = data.getimagepath(entity.img, entity.imgType)
    img = None
    try:
        img = tk.PhotoImage(imgPath)
        canvas.create_image(entity.x, entity.y, img)
    except IOError as e: print(e)
    finally:
        if not isinstance(img, type(None)): img.close()

main.py

e = player.Player(100, 200, "Ball_Grayed.png", 3)
gui.drawentity(e)

data.py

 cd = os.path.join(os.getcwd(), "resources")
 def getimagepath(imgName, imgType):
     return os.path.join(cd, imgType, imgName)

When running py main.py, I get the following output:

File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\main.py", line 12, in <module>
    gui.drawentity(e)
  File "S:\Users\Sean\Google Drive\cs\personal\BallAdventure\gui.py", line 22, in drawentity
    img = tk.PhotoImage(imgPath)
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4026, in __init__
    master = _get_default_root('create image')
  File "C:\Users\Sean\AppData\Local\Programs\Python\Python310\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

Everything looks fine to me, can anyone see what the problem is?

Sean McCallum
  • 158
  • 2
  • 10

1 Answers1

1

(see Nesi's comment)

It seems the tk.mainloop() call blocks (execution of the program halts there). I was only getting the error after exiting the window, which makes sense as the program essentially goes into a while True loop when mainloop() is called. Since I had been manually destroying the default root window, there was nothing to draw to upon continuing the code.

So, be careful where you put mainloop(), and know that it blocks.

(source/more info)

Sean McCallum
  • 158
  • 2
  • 10