【问题标题】:Why is Tkinter widget stored as None? (AttributeError: 'NoneType' object ...)(TypeError: 'NoneType' object ...) [duplicate]为什么 Tkinter 小部件存储为无? (AttributeError:'NoneType'对象...)(TypeError:'NoneType'对象...)[重复]
【发布时间】:2018-05-17 01:48:05
【问题描述】:
#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

【问题讨论】:

    标签: python tkinter widget attributeerror nonetype


    【解决方案1】:

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

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

    或:

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

    或:

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

    对于问题中的第二个代码 sn-p:

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

    应该分成两行:

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

    信息:This answer 是基于,如果不是大部分复制来自,this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 2015-02-27
      • 2021-05-26
      • 2019-03-10
      相关资源
      最近更新 更多