Por que o widget Tkinter é armazenado como Nenhum? (AttributeError: objeto 'NoneType' ...) (TypeError: objeto 'NoneType' ...) [duplicado]
Esta pergunta já tem uma resposta aqui:
Por que meus widgets Tkinter são armazenados como Nenhum? [duplicado] 1 resposta#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()
O código acima produz o erro:
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'
Da mesma forma, a parte do código:
#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()
produz o erro:
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
E nos dois casos:
>>>print(widget)
None
Por que é isso, por que éwidget
armazenado comoNone
, ou por que obtenho os erros acima quando tento configurar meus widgets?
Esta pergunta é baseada emesta e é solicitada uma resposta generalizada para muitas perguntas relacionadas e repetitivas sobre o assunto. Vejoesta para rejeição de edição.