Why is Tkinter widget stored as None? (AttributeError: ‘NoneType’ object …)(TypeError: ‘NoneType’ object …)

#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()

Above code produces the error:

Traceback (most recent call last):
  File "C:UsersuserDocumentsPythonotherscript.py", line 8, in <module>
    widget.config(text="Label A")
AttributeError: 'NoneType' object has no attribute 'config'

Similarly the code piece:

#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()

produces the error:

Traceback (most recent call last):
  File "C:UsersuserDocumentsPythonotherscript2.py", line 8, in <module>
    widget['command'] = root.destroy
TypeError: 'NoneType' object does not support item assignment

And in both cases:

>>>print(widget)
None

Why is that, why is widget stored as None, or why do I get the errors above when I try configuring my widgets?


This question is based on this and is asked for a generalized answer to many related and repetitive questions on the subject. See this for edit rejection.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

widget is stored as None because geometry manager methods grid, pack, place return None, and thus they should be called on a separate line than the line that creates an instance of the widget as in:

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

or:

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

or:

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

And for the 2nd code snippet in the question specifically:

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

should be separated to two lines as:

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

Info: This answer is based on, if not for the most parts copied from, this answer.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x