为什么 Tkinter 小部件存储为 None? (AttributeError: 'NoneType' 对象...)(TypeError: 'NoneType' 对象...) [重复]
- 2025-04-15 09:18:00
- admin 原创
- 25
问题描述:
#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/userDocumentsPythonotherscript.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/userDocumentsPythonotherscript2.py", line 8, in <module> widget['command'] = root.destroy TypeError: 'NoneType' object does not support item assignment
在这两种情况下:
>>>print(widget)
None
为什么会这样,为什么widget
存储为None
,或者为什么当我尝试配置我的小部件时会出现上述错误?
这个问题基于此,并要求对许多相关且重复的问题给出一个概括性的答案。请参阅此处了解编辑被拒的原因。
解决方案 1:
widget
存储为,None
因为几何管理器方法grid
、、返回,因此它们应该在与创建小部件实例的行不同的行pack
上调用,如下所示:place
`None`
widget = ...
widget.grid(..)
或者:
widget = ...
widget.pack(..)
或者:
widget = ...
widget.place(..)
对于问题中的第二个代码片段具体如下:
widget = tkinter.Button(...).pack(...)
应分为两行:
widget = tkinter.Button(...)
widget.pack(...)
信息:这个答案是基于这个答案的,如果不是大部分内容复制自这个答案的话。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD