0

I know there's already a thread related to this issue. But the answer doesn't work and no follow up since then.

This is the code I use to change image. The canvas becomes blank after clicking the button.

def change_image():
    photo2 = tk.PhotoImage(file="I.png")
    canvas.itemconfig(myimg,image=photo2)


root =tk.Tk()
root.title('Image show case')

canvas = Canvas(root,width=300, height=200, bg='white')
canvas.pack(expand=tk.YES, fill=tk.BOTH)
photo = tk.PhotoImage(file="V.png",master=root)
myimg = canvas.create_image(0,0,image=photo,anchor=tk.NW)

num1Entry = tk.Entry(root) #User choose the photo by typing names e.g. "cats", "cars"
num1Entry.pack(side=tk.LEFT)

Button = tk.Button(root,text='Clickme',command=change_image) #Button to change image
Button.pack(side = tk.LEFT )

Then I try to debug it by using the following code, in which I move the code of the function to the main code.

root =tk.Tk()
root.title('Image show case')

canvas = Canvas(root,width=300, height=200, bg='white')
canvas.pack(expand=tk.YES, fill=tk.BOTH)
photo = tk.PhotoImage(file="V.png",master=root)
myimg = canvas.create_image(0,0,image=photo,anchor=tk.NW)

photo2 = tk.PhotoImage(file="I.png")
canvas.itemconfig(myimg,image=photo2)


num1Entry = tk.Entry(root)
num1Entry.pack(side=tk.LEFT)


Button = tk.Button(root,text='Clickme',command=change_image)
Button.pack(side = tk.LEFT )

The second image shows correctly without the need of clicking the button.

So the problem occurs after clicking the button. However, I am unable pinpoint the exact problem.

Raven Cheuk
  • 2,903
  • 4
  • 27
  • 54
  • It's the same problem as mentioned in the big green box at the end of [the PhotoImage docs page](http://effbot.org/tkinterbook/photoimage.htm). So do something like `canvas.photo = photo2` in `change_image`. – PM 2Ring May 20 '18 at 09:17
  • Oh, I didn't know the solution is that simple. How come I didn't notice the green box in the documentation and spend almost half day figuring out what's going on... – Raven Cheuk May 20 '18 at 09:21
  • 1
    They use a special shade of green that's invisible until someone else talks about it. :) – PM 2Ring May 20 '18 at 09:26

0 Answers0