How to change image in canvas?[python tkinter]

那年仲夏 提交于 2019-12-25 16:58:08

问题


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()

回答1:


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)



回答2:


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()


来源:https://stackoverflow.com/questions/26586953/how-to-change-image-in-canvaspython-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!