Skip to content Skip to sidebar Skip to footer

Tkinter 'nonetype' Object Has No Attribute 'pack' (still Works?)

I'm fairly new to Python and have just started to play around with tkinter. Running the below code I get an attribute error for but1.pack() (NoneType object has no attribute pack).

Solution 1:

When you get an error such as 'NoneType' object has no attribute 'X', that means you have a variable whose value is None, and you are trying to do None.X(). It doesn't matter if you're using tkinter or any other package. So, you have to ask yourself, "why does my variable have the value None?"

The problem is this line:

but1 = tkinter.Button(window, text="Button1", command=btn1).grid(column=1, row=1)

In python, when you do foo=x(...).y(...), foo will always have the value of the last function called. In the case above, but will have the value returned by .grid(column = 1, row = 1), and grid always returns None. Thus, but1 is None, and thus you get `'NoneType' object has no attribute 'pack'".

So, the immediate fix is to move your call to grid to a separate line:

but1 = tkinter.Button(window, text="Button1", command=btn1)
but1.grid(column=1, row=1)

With that, the error will go away.

However, you have another problem. Calling grid and then later calling pack isn't going to do what you think it's going to do. You can only have one geometry manager in effect at a time for any given widget, and both grid and pack are geometry managers. If you do but1.grid(...) and later but1.pack(...), any effect that calling grid had will be thrown away, as if you had never called grid in the first place.

You have to decide whether you want to use grid, or whether you want to use pack, and use only one or the other for all widgets in your root window.

Solution 2:

Try changing this:

but1 = tkinter.Button(window, text="Button1", command=btn1).grid(column=1, row=1)

into this:

but1 = tkinter.Button(window, text="Button1", command=btn1)
but1.grid(column=1, row=1)

Chances are the .grid() method doesn't return a value.

Post a Comment for "Tkinter 'nonetype' Object Has No Attribute 'pack' (still Works?)"