2015-04-23 38 views
0

我有一個包含所有數據庫記錄的GUI。點擊「搜索」按鈕後,我希望從屏幕上清除所有記錄,並顯示與用戶搜索相關的記錄。我試圖引用我的標籤並調用「destroy」方法,如下所示:a.destroy()但該程序不會將這些標籤識別爲小部件。Python Tkinter:刪除標籤不起作用

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

編輯:分離的小部件分配和網格,但仍然面臨着同樣的問題。任何人都想幫助編程新手?

+0

我不認爲這直接回答你的問題,但你不能指定一個部件和其格同一條線。請參閱http://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-get – Kevin

+0

感謝凱文,我已經相應地改變了它 –

回答

1

爲了刪除某些內容,您必須有一個對它的引用。您不保存對正在創建的小部件的引用。嘗試將它們保存到列表或字典中。

在創建他們:

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

當你要刪除它們:

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