Tkinter帆布清爽

时间:2016-05-02 03:06:00

标签: python python-2.7 python-3.x tkinter tkinter-canvas

我正在使用Tkinter中的画布创建一个框架并在框架中显示图像。但我需要在循环中一个接一个地连续显示图像。但无法刷新画布。以下是我的代码。

cwgt=Canvas(self.parent.Frame1)
cwgt.pack(expand=True, fill=BOTH)
image1 = Image.open(image1)
image1 = ImageTk.PhotoImage(image1)
cwgt.img=image1
cwgt.create_image(0, 0, anchor=NW, image=image1)
cwgt.delete("all")

cwgt.delete("all")不起作用。

1 个答案:

答案 0 :(得分:1)

  

cwgt.delete(" all")无法正常工作。

好吧,不仅那条线不起作用,而且没有别的方法可行,所以我在这里向您展示一个基于您的文本(而不是您的代码)的最小运行示例来解释您如何实现它。

delete()方法执行您想要执行的操作。您可以将字符串 all 作为参数传递,以删除Tkinter.Canvas窗口小部件上显示的所有项目,或指定对所需项目的引用清除。

完整程序

'''
Created on May 2, 2016

@author: Billal Begueradj
'''
import Tkinter as Tk
from PIL import Image, ImageTk

class Begueradj(Tk.Frame):
    '''
    Dislay an image on Tkinter.Canvas and delete it on button click
    '''
    def __init__(self, parent):
        '''
        Inititialize the GUI with a button and a Canvas objects
        '''
        Tk.Frame.__init__(self, parent)
        self.parent=parent
        self.initialize_user_interface()

    def initialize_user_interface(self):
        """
        Draw the GUI
        """
        self.parent.title("Billal BEGUERADJ: Image deletion")       
        self.parent.grid_rowconfigure(0,weight=1)
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.config(background="lavender")    

        # Create a button and append it  a callback method to clear the image          
        self.deleteb = Tk.Button(self.parent, text = 'Delete', command = self.delete_image)
        self.deleteb.grid(row = 0, column = 0)

        self.canvas = Tk.Canvas(self.parent, width = 265, height = 200)  
        self.canvas.grid(row = 1, column = 0)   

        # Read an image from my Desktop
        self.image = Image.open("/home/hacker/Desktop/homer.jpg")
        self.photo = ImageTk.PhotoImage(self.image)        
        # Create the image on the Canvas     
        self.canvas.create_image(132,100, image = self.photo)

    def delete_image(self):
        '''
        Callback method to delete image
        '''
        self.canvas.delete("all")  


# Main method
def main():
    root=Tk.Tk()
    d=Begueradj(root)
    root.mainloop()

# Main program       
if __name__=="__main__":
    main()

如果您的Tkinter.Canvas小部件上有多个元素,并且您只想删除图像,则可以将其id指定为delete()方法,因为Tkinter.Canvas.create_image()会返回{{ 1}}创建的图像(虽然我在链接到的文档中没有提到)。

这意味着,在上面的代码中你可以运行:

id

self.ref_id = self.canvas.create_image(132,100, image = self.photo) 方法内部:

delete_image()

演示

这就是你得到的:

enter image description here

点击按钮后,图像将被清除:

enter image description here