user2666750
user2666750

Reputation: 602

How to change image in canvas?[python tkinter]

As below, I want to show an image in canvas using tkinter, and when a click the button, an other photo should be shown. But I failed. The first image shows well, but the image didn't change when I click the button

C = Tkinter.Canvas(top, bg="#fff", height=500, width=600)

// show image1 in canvas first and it works
itk = ImageTk.PhotoImage(img1)
C.create_image(300, 250, image=itk)
C.pack()


def changeImage():
    // I want to show image2 in canvas, but I fails
    print 'change image in canvas'
    itk2 = ImageTk.PhotoImage(img2)
    C.create_image(300, 250, image=itk2)

button = Tkinter.Button(top,text='click', command=changeImage)
button.pack()


top.mainloop()

Upvotes: 0

Views: 7028

Answers (2)

user4171906
user4171906

Reputation:

itk2 is destroyed once the function exits (and you will get syntax errors on other lines of the code). One solution, of many, is to keep it outside of the function. Consider this pseudo-code as I don't have time to test it.

class ImageTest():
    def __init__(self):
        self.root = tk.Tk()

        self.root.title('image test')
        self.image1 = ImageTk.PhotoImage(img1)
        self.image2 = ImageTk.PhotoImage(img2)

        self.displayed=True
        self.panel1 = Tkinter.Canvas(top, bg="#fff", height=500, width=600)
        self.panel1.create_image(300, 250, image=self.image1)
        self.panel1.pack()


        tk.Button(self.root, text="Next Pic", command=self.callback,
              bg="lightblue").pack()
        tk.Button(self.root, text="Exit", command=quit, bg="red").pack()

        self.root.mainloop()

    def callback(self):
        if self.displayed:
            self.panel1["image"]=self.image2
        else:
            self.panel1.config(image=self.image1)
        self.displayed=not self.displayed

IT=ImageTest()

Upvotes: 0

neiesc
neiesc

Reputation: 653

Changes one or more options for all matching items. 1

myimg = C.create_image(300, 250, image=itk)

def changeImage():
    // I want to show image2 in canvas, but I fails
    print 'change image in canvas'
    itk2 = ImageTk.PhotoImage(img2)
    C.itemconfigure(myimg, image=itk2)

Upvotes: 2

Related Questions