猿问

为什么Tkinter小部件存储为None?(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,或者为什么在尝试配置窗口小部件时出现上述错误?


这个问题是基于此,并问了广义回答很多关于这个主题相关的和重复的问题。参见此以拒绝编辑。


PIPIONE
浏览 414回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答