Reputation: 602
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
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