-1

Am new to python and tkinter. Trying to write a simple python code to get the username and print it

So, I tried the below

root = Tk() # line 1
e = Entry(root, width = 50).pack() # line 2 option 1 - results in below error as shown below
e = Entry(root, width = 50) # line 2 option 2 - works fine
e.pack() # line 3 option 2 - works fine
def clicking():
    word = "Hello " + e.get()
    myLabel = Label(root,text=word).pack()
myButton = Button(root, text = "Generate", command = clicking).pack()

When I click on Generate button, I expect to see an output like "Hello John"

But I get the below error when I write the line 2 as shown in line 2 option 1 above

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\test\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\test~1\AppData\Local\Temp/ipykernel_8876/988003047.py", line 4, in clicking
    word = "Hello " + e.get()
AttributeError: 'NoneType' object has no attribute 'get'

However, when I write the line 2 as two separate lines as shown in line 2 option 2 and line 3 option 2, it works fine and I get the below output.

enter image description here

Can help me understand why does this happen? what is the difference between packing together with root and not with root?

The Great
  • 7,215
  • 7
  • 40
  • 128
  • first: if you use `variable = Widget().pack()` then you assign `None` to variable because `pack()`, `grid()`, `place()` return `None`. And this is the problem. You should do it in two lines `variable = Widget()` and `variable.pack()` – furas Nov 22 '21 at 10:14
  • 1
    I am unable to delete this question as it has already been answered. Anyway, similar question can be found here - https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-attribute-name – The Great Nov 22 '21 at 10:31

1 Answers1

1

When you use

variable = Widget().pack()

then you assign None to variable because pack(), grid(), place() return None.

You should do it in two lines

variable = Widget() 
variable.pack()

First line assigns widget to variable.
In second line you use variable to access this widget.

furas
  • 134,197
  • 12
  • 106
  • 148