我该如何删除tkinter Frame中的内容?

3
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import cv2

def main():
    root = Tk()
    root.title("face")
    w=root.winfo_screenwidth()
    h=root.winfo_screenheight()
    root.geometry("%dx%d" % (w, h))

    def openimage(): #in this part I just want to keep just one picture in Frame
        fname = filedialog.askopenfilename()
        image = Image.open(fname)
        (width, height)=image.size
        if width>=height:
            new_width=t1.winfo_width()
            new_height=int(height*t1.winfo_width()/width)
            image = image.resize((new_width, new_height), Image.ANTIALIAS)

        else:
            new_height=t1.winfo_height()
            new_width=int(width*t1.winfo_height()/height)
            image = image.resize((new_width, new_height), Image.ANTIALIAS)

        render = ImageTk.PhotoImage(image)
        img = Label(t1, image=render)
        img.image = render
        img.place(x=0, y=0)

    def finish():
        exit()


    menubar = Menu(root)
    root.config(menu=menubar)

    menu1 = Menu(root)
    menu1.add_command(label='openphoto', command=openimage)
    menu1.add_command(label='get')
    menu1.add_command(label='save')

    menu2 = Menu(root)
    menu2.add_command(label='read')
    menu2.add_command(label='training')

    menu3 = Menu(root)
    menu3.add_command(label='openphotos')
    menu3.add_command(label='dis')

    menu4 = Menu(root)
    menu4.add_command(label='quit', command=finish)

    menubar.add_cascade(label="catch", menu=menu1)
    menubar.add_cascade(label="train", menu=menu2)
    menubar.add_cascade(label="distinguish", menu=menu3)
    menubar.add_cascade(label="exit", menu=menu4)



    t1=Frame(width=500,height=500, bg='gray')
    t1.grid(padx=100, pady=100)

    root.mainloop()



if __name__ =='__main__':

    main()

我希望能够清空框架中的内容,或者在选择另一张图片时不显示之前的图片。每次选择一张图片时,它与上次选择使用的参数无关。因此,我想每次选择一张图片时都清空框架。我已经尝试了很多方法,但不知道该如何清空。

1个回答

4
为了清除 tkinter 中 Frame() 实例 frame 中的小部件,您可以使用以下代码:
for widget in frame.winfo_children():
    widget.destroy()

frame.winfo_children() 返回 frame 中所有小部件的列表,然后我们循环遍历它们并使用 destroy() 销毁它们。


阿特米斯,你是传奇! - Benjamin McDowell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接