因为您使用了相同的变量
searched_label
对于所有标签,只有最后一个标签将被该行销毁
searched_label.destroy()
您可以使用列表存储创建的标签,然后通过此列表销毁所有标签:
labels = [] # list to store the labels
# assume the posted code is inside a function
def show_tracking():
# destroy existing labels
for lbl in labels:
lbl.destroy()
labels.clear() # clear the list
# populate new labels
search = tracking_id_entry.get()
sql = "SELECT * FROM table_desc WHERE tracking_id = %s"
name = (search,)
my_cursor.execute(sql, name)
result = my_cursor.fetchall()
if not result:
result = "Tracking ID Not Found..."
searched_label = Label(screen, text=result)
searched_label.grid(row=7, columnspan=2, sticky=EW)
labels.append(searched_label) # add the label to the list
else:
for index, x in enumerate(result):
num = 0
index += 7
for y in x:
searched_label = Label(screen, text=y)
searched_label.grid(row=index, column=num)
labels.append(searched_label) # add the label to the list
num += 1