destroy方法的属性错误

时间:2014-12-26 16:20:55

标签: python tkinter

如果我在“输入”框保持为空时单击按钮,则会出现以下错误。 输入值并单击后,它会无错误地运行,但不会在将输入框留空并单击

时运行

错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:/Python27/tew.py", line 31, in retrieve_inpu
    self.label.destroy()
AttributeError: 'NoneType' object has no attribute 'destroy'

编码:

import Tkinter as tki
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
                         user="root", # your username
                          passwd="mysql", # your password
                          db="sakila") # name of the data base
cursor = db.cursor()

class App(object):
     def __init__(self,root):
         self.root = root

         self.txt_frm = tki.Frame(self.root, width=900, height=900)
         self.txt_frm.pack(fill="both", expand=True)
         button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
         button3.grid(column=0,row=2)
         self.entry = tki.Entry(self.txt_frm)
         self.entry.grid(column=1,row=0)

         #place holder for label variable
         self.label = None
         self.label1=None

     def retrieve_inpu(self):
        ent = self.entry.get()


        cursor.execute('SELECT A1,A2,A3 FROM adarsh1 WHERE A1=%s', (ent,))
        row = cursor.fetchone()
        if row is None:
           self.label.destroy()
           self.label1.destroy()
           #or self.label['text'] = ''
           return
        #destroy the widget if it has been created
        #you will have a bunch of orphans if you don't
        if self.label:
            self.label.destroy()

        self.label = tki.Label(self.txt_frm,text=row[1])
        self.label.grid(column=0,row=3)

        if self.label1:
            self.label1.destroy()

        self.label1 = tki.Label(self.txt_frm,text=row[2])
        self.label1.grid(column=0,row=4)            



root = tki.Tk()
app = App(root)
root.mainloop()

1 个答案:

答案 0 :(得分:2)

阅读错误:

    self.label.destroy()
AttributeError: 'NoneType' object has no attribute 'destroy'

这意味着self.labelNone,因此您无法销毁它。您可以通过执行与稍后在代码中执行相同的操作来修复此问题,并在销毁之前检查它是否为None

if row is None:
    if self.label:
        self.label.destroy()
    if self.label1:
        self.label1.destroy()
    #or self.label['text'] = ''
    return