Search code examples
pythontkintertkinter-canvastkinter-entrytkinter-layout

Python tkinter - pack append vs pack separate from root


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?


Solution

  • 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.