#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
или почему я получаю сообщения об ошибках, описанных выше, когда пытаюсь настроить виджеты?
Этот вопрос основан на этом и задается обобщенный ответ на многие связанные и повторяющиеся вопросы по этому вопросу. См. это для отклонения редактирования.