我正在尝试创建一个按钮,该按钮将清除画布,然后将图像放入从Tkinter文件对话框中选择的画布中。我正在使用canvas.delete("all")
方法shared here尝试在选择新图像之前清除画布,但是新图像出现在现有图像上方,而不是替换它。
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
from PIL import Image, ImageTk
root = Tk()
canvas1 = Canvas(root, width=500, height=500)
canvas1.pack()
class widgets:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.pack()
self.button1 = Button(self.myContainer1, command=self.button1click)
self.button1.config(text="Select Image")
self.button1.pack(side=TOP)
def button1click(self):
canvas1.delete("all")
path = tkFileDialog.askopenfilename(filetypes=[("Image File", '.png')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
imglabel = Label(canvas1, image=tkimage)
imglabel.image = tkimage
imglabel.pack()
widgets = widgets(root)
root.mainloop()