I've been trying out my hand with Tkinter in building a GUI where users can track an item they enter the ID for. Pretty much all of it is done, but I'm running into an issue with using .destroy()
What I would like to happen is when a user selects a button, it destroys all displayed table results. Right now, the table results remain without error. Based on the code snippet below, does anything stand out?
global searched_label
searched_label.destroy()
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)
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)
num = 1
CodePudding user response:
Since you used same variable searched_label
for all the labels, so only the last label will be destroyed by the line searched_label.destroy()
.
You can use a list to store the created labels and then you can go through this list to destroy all the labels:
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