Why is Tkinter widget stored as None? (AttributeError: 'NoneType' object ...)(TypeError: 'NoneType' object ...)

Why is Tkinter widget stored as None? (AttributeError: 'NoneType' object ...)(TypeError: 'NoneType' object ...)

#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,或者为什么我在尝试配置小部件时出现上述错误?


此问题基于 this and is asked for a generalized answer to many related and repetitive questions on the subject. See this 编辑拒绝。

widget 存储为 None 因为几何管理器方法 grid, pack, place return None,因此应该在 上调用它们]separate line 而不是创建小部件实例的行,如:

widget = ...
widget.grid(..)

或:

widget = ...
widget.pack(..)

或:

widget = ...
widget.place(..)

对于问题中的第二个代码片段:

widget = tkinter.Button(...).pack(...)

应该分成两行:

widget = tkinter.Button(...)
widget.pack(...)

信息: is based on, if not for the most parts copied from, this answer.