2012-10-21 48 views
2

我遇到了这个问题,我不明白为什么。AttributeError:'NoneType'对象没有属性'delete'

我从我的应用程序中取得了我的代码,并且创建了这个测试代码,因此您不必通过一堆垃圾来查看我所要求的内容。

我在其他代码中工作。但在比较这两者之后,我不能在我的生活中弄清楚这一点。

在此应用程序中,我收到错误“AttributeError:'NoneType'对象没有属性'delete'”。

import Tkinter as tk 

def main(): 
    mainWindow = tk.Tk() 
    v = tk.StringVar() 
    entryBox = tk.Entry(mainWindow, textvariable=v).grid(column=0, row=1) 
    def test(): 
     entryBox.delete(0,20) 
    testButton = tk.Button(mainWindow, text='Go!', command=test, padx=10).grid(row=2, column=0) 
    tk.mainloop() 
main() 

回答

5

在这一行:

entryBox = tk.Entry(mainWindow, textvariable=v).grid(column=0, row=1) 

电网不返回任何东西,所以entryBox为None,其不具有删除方法。您必须将entryBox设置为tk.Entry(mainWindow, textvariable=v),然后拨打grid方法entryBox

+0

只要我建立我的声望,我就会投票赞成...这是修复。谢谢 !!!!!! –

0

,你在这里声明的entryBox当你正在尝试做的呼吁是delete尚未得到呢。如果你想要一个简单的方法来重现错误。

In [1]: x = None 
In [2]: x.delete 
AttributeError: 'NoneType' object has no attribute 'delete' 

要解决这个问题,你可以包装entryBox或确保获得它。

if entryBox: 
    entryBox.delete(0, 20) 
+0

不,这不是在这种特定情况下的问题。 –

1

发生这种情况的原因是因为您将它网格化为相同的变量。如果你改变你的代码下面,它应该工作:

import Tkinter as tk 
def main(): 
    mainWindow = tk.Tk() 
    v = tk.StringVar() 
    entryBox = tk.Entry(mainWindow, textvariable=v) 
    def test(): 
     entryBox.delete(0,20) 
    testButton = tk.Button(mainWindow, text='Go!', command=test, padx=10) 
    testButton.grid(row=2, column=0) 
    entryBox.grid(column=0, row=1) 
    tk.mainloop() 
main() 

这部作品的原因是因为grid()不返回任何东西。

+0

这有效。谢谢 !!! 只要我建立我的声望,我会回来并投票赞成:) 谢谢! –