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() 返回图像的id创建(虽然我链接到的文档中没有提到)。
这意味着,在上面的代码中你可以运行:
self.ref_id = self.canvas.create_image(132,100, image = self.photo)
在delete_image()方法内部:
self.canvas.delete(self.ref_id)
演示
这就是你得到的:
点击按钮后,图片会被清空: