为什么Tkinter小部件存储为None?(AttributeError:“ NoneType”对象...)(TypeError:“ NoneType”对象...)[重复]
这个问题已经在这里有了答案 :
为什么我的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
,或者为什么在尝试配置窗口小部件时出现上述错误?