0

My full code

from tkinter import *
i=0
 for i in range(10) :
 window = Tk()
 window.title('add image')
 window = Canvas(window,width= 600, height= 600)
 window.pack()
 image=PhotoImage(file=r"C:\\Users\\Konstantinos\\New folder\\hello.png")
 window.create_image(0,0, anchor = NW, image=image)
window.mainloop()

The error when i run the program

File "C:\Programms\Lib\tkinter\__init__.py", line 2832, in _create
return self.tk.getint(self.tk.call(
                      ^^^^^^^^^^^^^
_tkinter.TclError: image "pyimage2" doesn't exist

The error when i debug the program

Exception has occurred: TclError
image "pyimage2" doesn't exist
File "C:\Users\Konstantinos\New folder\demo.py", line 9, in <module>
window.create_image(0,0, anchor = NW, image=image)

So basically, the program opens an image multiple times. When th program is not in a loop it works but when i put it in a loop it gives me the error. Because i recently started programming i dont really know how to solve the problem and I have looked in other threads with the similar problem but none apply to me. I will appreciate any answer

1 Answers1

2

The error comes from multiple Tk instances. The fix is only having one Tk instance. Since your intention was multiple windows, you can look into this answer: https://stackoverflow.com/a/36316105/9983213. A smaller example is:

import tkinter as tk

root = tk.Tk()
for i in range(5):
    top = tk.Toplevel(root)

root.mainloop()

Edited code and explanation under for showing images

For each window you create a canvas and assign the image to it. If you are using the same image it isn't necessary to create a new image every loop so we do it once. If you are going to have the image loaded inside a function you most likely need to have canvas.image = myImage after canvas.create_image. This is because of a bug where images created by PhotoImage can "disappear" when the variable gets out of scope. This is explained as in this answer: https://stackoverflow.com/a/27430839/9983213. Also, the canvas part not inside the for-loop is there to also show an image on the Tk window and not just the Toplevel windows.

import tkinter as tk

root = tk.Tk()
myImage = tk.PhotoImage(file="image.png")

canvas = tk.Canvas(root, width=200, height=200)
canvas.pack()
canvas.create_image(100, 100, image=myImage)
canvas.image = myImage

for i in range(5):
    top = tk.Toplevel(root)
    canvas = tk.Canvas(top, width=200, height=200)
    canvas.pack()
    canvas.create_image(100, 100, image=myImage)

root.mainloop()
Nico Derp
  • 61
  • 3