1

I have problem with updating picture in canvas in tkinter. I'm using Python 3.3.

from tkinter import *

class Testi():
    def __init__(self):
        self.canvas = Canvas(root, width = 800, height = 480)
        self.img = PhotoImage(file="title.pgm")
        self.imgArea = self.canvas.create_image(0, 0, anchor = NW, image = self.img)
        self.canvas.pack()
        self.but1 = Button(root, text="press me", command=lambda: self.changeImg())
        self.but1.place(x=10, y=500)

    def changeImg(self):
        newimg = PhotoImage(file="cell.pgm")
        self.canvas.itemconfig(self.imgArea, image = newimg)

root = Tk()
root.geometry("800x600")
app = Testi()
root.mainloop() 

At first the image is visible but after pressing button, it goes blank. I have read many similar questions but none of those had any help.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
user3407101
  • 67
  • 2
  • 5

1 Answers1

3

Like the original image, you need to keep a reference to the new image, or it will get garbage collected prematurely. Just overwrite the old image sitting at self.img.

def changeImg(self):

    self.img = PhotoImage(file="cell.pgm")

    self.canvas.itemconfig(self.imgArea, image = self.img)
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Thank you for fast and very helpful answer! I thought that mention about self.imgArea in itemconfig is enough but clearly it wasn't. – user3407101 Mar 04 '15 at 18:23