为什么Tkinter小部件存储为None?(AttributeError:“ NoneType”对象...)(TypeError:“ NoneType”对象...)[重复]

发布于 2021-01-29 16:11:53

这个问题已经在这里有了答案

为什么我的Tkinter小部件被存储为None?[重复] (1个答案)

3年前关闭。

#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


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


widget[‘command’] = root.destroy
TypeError: ‘NoneType’ object does not support item assignment


在两种情况下:

>>>print(widget)
None

为什么那样,为什么widget存储为None,或者为什么在尝试配置窗口小部件时出现上述错误?


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

关注者
0
被浏览
171
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    widget存储为None因为几何管理方法gridpackplace返回None,因此,他们应该在一个被称为
    独立的线 比创建控件的实例作为行:

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

    要么:

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

    要么:

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

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

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

    应该分成两行,分别是:

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

    信息:该答案基于(如果不是从该答案
    复制 的大部分内容中)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看