问题描述
#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'
类似的代码段:
Similarly the code piece:
#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
在两种情况下:
And in both cases:
>>>print(widget)
None
为什么?为什么widget
存储为None
?为什么在尝试配置窗口小部件时出现上述错误?
Why is that, why is widget
stored as None
, or why do I get the errors above when I try configuring my widgets?
此问题基于 this 和要求回答有关该主题的许多相关和重复性问题.参见此以了解编辑拒绝.
This question is based on this and is asked for a generalized answer to many related and repetitive questions on the subject. See this for edit rejection.
推荐答案
widget
存储为None
,因为几何管理器方法 grid
, pack
, place
返回None
,因此应在单独行,而不是创建窗口小部件实例的行,如下所示:
widget
is stored as None
because geometry manager methods grid
, pack
, place
return None
, and thus they should be called on a separate line than the line that creates an instance of the widget as in:
widget = ...
widget.grid(..)
或:
widget = ...
widget.pack(..)
或:
widget = ...
widget.place(..)
针对该问题的第二个代码段:
And for the 2nd code snippet in the question specifically:
widget = tkinter.Button(...).pack(...)
应分为两行,分别为:
widget = tkinter.Button(...)
widget.pack(...)
Info: This answer is based on, if not for the most parts copied from, this answer.
这篇关于为什么Tkinter小部件存储为None? (AttributeError:'NoneType'对象...)(TypeError:'NoneType'对象...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!