为什么Tkinter小部件存储为None? (AttributeError:'NoneType'对象...)(TypeError:'NoneType'对象......)

时间:2017-12-03 13:52:20

标签: python tkinter widget attributeerror nonetype

#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,并要求对该主题的许多相关和重复性问题进行概括性回答。有关编辑拒绝,请参阅this

1 个答案:

答案 0 :(得分:2)

widget存储为None,因为几何管理器方法gridpackplace返回None,因此应调用它们在单独的行上,而不是创建小部件实例的行,如:

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

或:

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

或:

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

特别是问题中的第二个代码片段:

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

应分为两行:

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

信息:This answer基于this answer复制的大多数部分。