#AttributeError: 'NoneType' object has no attribute ... Example
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
root = tk.Tk()
widget = tk.Label(root, text="Label 1").grid()
widget.config(text="Label A")
root.mainloop()
以上代码产生错误:
Traceback (most recent call last): File "C:\Users\user\Documents\Python\other\script.py", line 8, in <module> widget.config(text="Label A") AttributeError: 'NoneType' object has no attribute 'config'
同样代码:
#TypeError: 'NoneType' object does not support item assignment Example
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
root = tk.Tk()
widget = tk.Button(root, text="Quit").pack()
widget['command'] = root.destroy
root.mainloop()
产生错误:
Traceback (most recent call last): File "C:\Users\user\Documents\Python\other\script2.py", line 8, in <module> widget['command'] = root.destroy TypeError: 'NoneType' object does not support item assignment
在这两种情况下:
>>>print(widget)
None
为什么会这样,为什么widget
存储为None
,或者为什么在尝试配置我的小部件时会出现上述错误?
答案 0 :(得分:2)
widget
存储为None
,因为几何管理器方法grid
,pack
,place
返回None
,因此应调用它们在单独的行上,而不是创建小部件实例的行,如:
widget = ...
widget.grid(..)
或:
widget = ...
widget.pack(..)
或:
widget = ...
widget.place(..)
特别是问题中的第二个代码片段:
widget = tkinter.Button(...).pack(...)
应分为两行:
widget = tkinter.Button(...)
widget.pack(...)
信息:This answer基于this answer的复制的大多数部分。