简体   繁体   English

销毁方法的属性错误

[英]attribute error on destroy method

I am getting the following error,if i click the button when the Entry box has kept empty. 如果在“输入”框保持空白时单击按钮,则会收到以下错误。 It runs without errors once i enter the values and click but not when leaving the entrybox empty and clicking 输入值并单击后,它将运行无错误,但将输入框保留为空并单击时,它不会运行

Error: 错误:

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'

Coding: 编码:

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

Read the error: 读取错误:

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

This means that self.label is None , so you can't destroy it. 这意味着self.labelNone ,因此您无法销毁它。 You could fix this by doing the same thing as you do later in the code, and checking if it is None before you destroy it: 您可以通过执行与稍后在代码中相同的操作来解决此问题,并在销毁它之前检查它是否为None

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM