删除输入框

Deleting entry boxes

我正在尝试构建一个程序来收集用户数据。为此,用户设置输入框的数量并创建输入框。我的问题与用户设置 4 个输入框时创建 4 个输入框有关,之后,用户可以设置 2 个输入框但它仍然显示最后 4 个输入框,我的意思是,我需要删除所有输入框之前由用户创建并创建新的 ones.I 尝试了 winfo_children() 但它消除了所有输入框,甚至消除了用户设置输入框数量的输入框。 请你帮帮我好吗? 提前谢谢你,

from tkinter import *

# Creating main screen
root  = Tk() 

# Function to set amount of entry boxes
def boxes():

    # Saving amount of boxes
    amount = int(number_boxes.get())

    for i in range(amount):
        for y in range(4):
            set_boxes = Entry(root, borderwidth=3)
            set_boxes.grid(row=i+4, column=y)
     
# Creating label for number of boxes
label_number_boxes = Label(root, text='Enter the number of boxes')
# Showing in screen
label_number_boxes.grid(row=0, column=0)

# Creating number of boxes
number_boxes = Entry(root, width=20, bg='white', fg='black', borderwidth=3)
# Showing in screen
number_boxes.grid(row=1, column=0)

# Creating button to set the amount of boxes
button_number_boxes = Button(root, text='Set amount of boxes', command=boxes)
# Showing in screen
button_number_boxes.grid(row=2, column=0)

# Creating infinite loop to show in screen
root.mainloop()

使用列表存储那些 Entry 小部件,然后您可以使用此列表在创建新小部件之前销毁 Entry 小部件:

entries = []

# Function to set amount of entry boxes
def boxes():
    # clear old entry boxes
    for w in entries:
        w.destroy()
    entries.clear()

    # Saving amount of boxes
    amount = int(number_boxes.get())

    for i in range(amount):
        for y in range(4):
            set_boxes = Entry(root, borderwidth=3)
            set_boxes.grid(row=i+4, column=y)
            entries.append(set_boxes) # save the Entry widget