tkinter 'NoneType' object has no attribute 'pack' (Still works?)

房东的猫 提交于 2019-12-02 12:05:19

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!