如下所示,我想使用tkinter在画布上显示图像,当单击按钮时,应显示另一张照片。但我失败了。第一张图片显示效果不错,但单击按钮
时图像没有变化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()
答案 0 :(得分:1)
更改所有匹配项的一个或多个选项。 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)
答案 1 :(得分:0)
一旦函数退出,itk2就会被销毁(并且你会在代码的其他行上得到语法错误)。许多解决方案中的一个解决方案是将其置于功能之外。考虑这个伪代码,因为我没有时间对其进行测试。
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()