A.M.
A.M.

Reputation: 23

Python Tkinter: Delete label not working

I have a GUI that contains all the database records. Upon clicking the "search" button, I want all the records to be cleared from the screen, and the records relevant to the user's search to appear. I am trying to reference my labels and call the "destroy" method like this: a.destroy() but the program is not recognizing these labels as widgets.

class DBViewer:
    def __init__(self, rows):
        # Display all records
            row_for_records = 2
            for record in rows:
                a = tkinter.Label(self.main_window, text=record[0])
                a.grid(row=row_for_records, column=0)
                b = tkinter.Label(self.main_window, text=record[1])
                b.grid(row=row_for_records, column=1)
                # More labels here

            self.display_rows(rows)
            tkinter.mainloop()

    def display_rows(self, rows):
        # Where I'm having trouble

    def main():
        global db
        try:
            dbname = 'books.db'
            if os.path.exists(dbname):
                db = sqlite3.connect(dbname)
                cursor = db.cursor()
                sql = 'SELECT * FROM BOOKS'
                cursor.execute(sql)
                rows = cursor.fetchall()
                DBViewer(rows)
                db.close()

Edit: Separated widget assignment and grid but still facing have the same problem. Anyone want to help out a programming newbie?

Upvotes: 0

Views: 1740

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

In order to delete something, you must have a reference to it. You aren't saving references to the widgets you are creating. Try saving them to a list or dictionary.

When creating them:

...
self.labels = []
for record in rows:
    a = Tkinter.Label(...)
    self.labels.append(a)
    ...

When you want to delete them:

for label in self.labels:
    label.destroy()

Upvotes: 1

Related Questions