Python Tkinter:删除标签不起作用

2024-04-19 17:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含所有数据库记录的GUI。单击“搜索”按钮后,我希望从屏幕上清除所有记录,并显示与用户搜索相关的记录。我试图引用我的标签并像这样调用“destroy”方法:a.destroy(),但是程序没有将这些标签识别为小部件。在

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()

编辑:分开的小部件分配和网格,但仍然面临相同的问题。有人想帮编程新手吗?在


Tags: selffordbmaintkinterdef记录标签
1条回答
网友
1楼 · 发布于 2024-04-19 17:39:28

要删除某些内容,必须有对它的引用。您没有保存对正在创建的小部件的引用。尝试将它们保存到列表或词典中。在

创建它们时:

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

当您要删除它们时:

^{pr2}$

相关问题 更多 >