如何在画布中更改图像? [python tkinter]

2024-10-01 15:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如下所示,我想用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()

Tags: in图像imagetkintertopshowcreate按钮
2条回答

更改所有匹配项的一个或多个选项。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)

一旦函数退出,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()

相关问题 更多 >

    热门问题