首页 > 解决方案 > 使用 grid() 函数的“AttributeError”

问题描述

使用 gride 时出现错误:“AttributeError:'NoneType' 对象没有属性 'grid'”。

这是我的代码:


    root = tk.Tk()
    root.configure(bg="black")

    # Creates labels
    tk.Label(root, image=logo1).pack()

    # Creates buttons
    tk.Button(root, image=logo2, command=root.destroy).pack().grid(row=0, column=0)
    tk.Button(root, image=logo3, command=root.destroy).pack().grid(row=0, column=0)

    root.mainloop()


标签: pythonuser-interfacetkinter

解决方案


您同时使用了两个包装管理器,但您使用错误。

打包调用将返回 None,并且您正在尝试将网格调用分配给该 None。

这样做:

tk.Button(root, image=logo2, command=root.destroy).grid(row=0, column=0)
tk.Button(root, image=logo3, command=root.destroy).grid(row=0, column=0)

或者使用包管理器而不是网格:

tk.Button(root, image=logo2, command=root.destroy).pack()
tk.Button(root, image=logo3, command=root.destroy).pack()

推荐阅读