简体   繁体   中英

How can I remove items on a Tkinter window?

I am trying to clear the items on the window without closing the root window just the items visible.While everything is deleted Some of the labels are still left.I created a button "close" to remove the items.My code is as below;

from tkinter import*
root = Tk()
root.geometry("480x480")
# Node
myLabel1 = Label(root, text=f'Node')
myLabel1.grid(row=0, column=0)
rows = []  # show the input entry boxes
for i in range(6):
    # name
    entry = Entry(root, width=5, bd=5)
    entry.grid(row=2+i, column=0)
    # x
    myLabel2 = Label(root, text=f'x{i}')
    myLabel2.grid(row=2+i, column=1)
    entry_x = Entry(root, width=5, bd=5)
    entry_x.grid(row=2+i, column=2)
    # y
    myLabel3 = Label(root, text=f'y{i}')
    myLabel3.grid(row=2+i, column=3)
    entry_y = Entry(root, width=5, bd=5)
    entry_y.grid(row=2+i, column=4)
    # save current input row
    rows.append((entry, entry_x, entry_y))
def close():
    for name,ex,ey in rows:
        name.destroy()
        ex.destroy()
        ey.destroy()
    myLabel3.destroy()
    myLabel2.destroy()
    myLabel1.destroy()
    myButton_close.destroy()
myButton_close = Button(root, text="close",padx = 10,pady = 10, command=close)
myButton_close.grid(row=8, column=6)
root.mainloop()

where could i be going wrong?

Create a Frame to hold the widgets and then you can destroy the frame to clear the window:

from tkinter import *

root = Tk()
root.geometry("480x480")

frame = Frame(root)
frame.pack(fill=BOTH, expand=1)

# Node
myLabel1 = Label(frame, text=f'Node')
myLabel1.grid(row=0, column=0)
rows = []  # store the input entry boxes
for i in range(6):
    # name
    entry = Entry(frame, width=5, bd=5)
    entry.grid(row=2+i, column=0)
    # x
    myLabel2 = Label(frame, text=f'x{i}')
    myLabel2.grid(row=2+i, column=1)
    entry_x = Entry(frame, width=5, bd=5)
    entry_x.grid(row=2+i, column=2)
    # y
    myLabel3 = Label(frame, text=f'y{i}')
    myLabel3.grid(row=2+i, column=3)
    entry_y = Entry(frame, width=5, bd=5)
    entry_y.grid(row=2+i, column=4)
    # save current input row
    rows.append((entry, entry_x, entry_y))

def close():
    frame.destroy()

myButton_close = Button(frame, text="close", padx=10, pady=10, command=close)
myButton_close.grid(row=8, column=6)

root.mainloop()

Grouping widgets into a frame make it easier to clear certain part of the window.

You create the labels in a loop but you are not saving any reference to the labels except for the last myLabel2/3. However you can ask a widget about its children, and then destroy them all:

def close():
    for widget in root.winfo_children():
        widget.destroy()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM