Skip to main content
 首页 » 编程设计

python之如何删除 tkinter Frame 中的内容

2024年09月07日9over140

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() 

我想清除Frame中的内容,或者让之前的图片不显示在Frame中,而我选择了另一张图片。每次选择一张图片,与上次选择时使用的参数无关。所以每次选图的时候都想清空一个Frame。我尝试过很多方法。我不知道如何清除它。

请您参考如下方法:

要从 tkinter Frame() 实例 frame 中清除小部件,您可以使用以下代码:

for widget in frame.winfo_children(): 
    widget.destroy() 

frame.winfo_children()返回 frame 中所有小部件的列表,然后我们遍历它们并将它们全部destroy()。