NoneType'对象没有属性'config

15 投票
4 回答
53454 浏览
提问于 2025-04-18 03:50

我这里想做的是给我已有的按钮添加一张图片,然后根据点击或者鼠标悬停的情况来改变这张图片。我看到的所有例子都使用了 .config() 这个方法。

我真搞不懂为什么它不知道按钮对象是什么。有趣的是,如果我修改按钮的定义,把图片选项加上,一切就正常了。但是,如果加上这个选项后,我似乎就不能用 .config() 来修改它了。

PlayUp = PhotoImage(file=currentdir+'\Up_image.gif')
PlayDown = PhotoImage(file=currentdir+'\Down_image.gif')
#Functions
def playButton():
    pButton.config(image=PlayDown)
pButton = Button(root, text="Play", command="playButton").grid(row=1)
pButton.config(image=PlayUp)

4 个回答

1

是的,我发现用一行代码来打包按钮,比如说 btt = Button(root,text='Hi Button').pack(),会搞乱对象的数据类型,导致它变成 NoneType。但是如果你像这样在后面单独使用 .packbtt.pack(),就能解决大部分和tkinter相关的问题。

1
canvas = tk.Tk()
canvas.title("Text Entry")

text_label = ttk.Label(canvas, text = "Default Text")
text_label_1 = ttk.Label(canvas, text = "Enter Your Name: ").grid(column = 0, row = 1)
text_variable = tk.StringVar()
text_entry = ttk.Entry(canvas, width = 15, textvariable = text_variable)
text_entry.grid(column = 1, row = 1)
def change_greeting():
    text_label.configure(text = "Hello " + text_variable.get())
event_button = ttk.Button(canvas, text="Click me and see what happens", command = change_greeting).grid(column = 2, row = 1)
text_label.grid(column = 0, row = 0)
canvas.resizable(False, False)
canvas.mainloop()

在上面的代码中,text_label.grid(column = 0, row = 0) 是放在最后的,也就是说在对标签的所有操作完成后才执行这行代码。
如果在上面的代码中直接写成 text_label = ttk.Label(canvas, text = "Default Text").grid(column = 0, row = 0),那么就会出现错误。因此,在显示对象时要小心谨慎。

1

我不知道这是否对类似的情况有帮助:

mywidget = Tkinter.Entry(root,textvariable=myvar,width=10).pack()
mywidget.config(bg='red')

这会产生这个错误:

AttributeError: 'NoneType' object has no attribute 'config'

但是如果我把代码写在不同的行上,一切就运行得很顺利:

mywidget = Tkinter.Entry(root,textvariable=myvar,width=10)
mywidget.pack()
mywidget.config(bg='red')

我不太明白这个问题,但我花了很多时间才解决... :-(

57
pButton = Button(root, text="Play", command="playButton").grid(row=1)

这里你创建了一个类型为 Button 的对象,但你马上就调用了它的 grid 方法,这个方法返回的是 None。所以,pButton 被赋值为 None,这就是为什么下一行代码会出错的原因。

你应该这样做:

pButton = Button(root, text="Play", command="playButton")
pButton.grid(row=1)
pButton.config(image=PlayUp)

也就是说,首先你创建按钮并把它赋值给 pButton然后 再对它进行其他操作。

撰写回答