【问题标题】:'NoneType' object has no attribute 'config' [duplicate]“NoneType”对象没有属性“config”[重复]
【发布时间】:2014-04-22 22:38:37
【问题描述】:

我在这里要做的是将图像添加到我拥有的按钮中,然后根据单击或悬停更改图像。我遵循的所有示例都使用.config() 方法。

对于我的生活,我无法弄清楚为什么它不知道按钮对象是什么。有趣的是,如果我修改 Button 定义行以包含图像选项,一切都很好。但是,似乎我无法使用.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)

【问题讨论】:

    标签: python image button nonetype


    【解决方案1】:
    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然后你在它上面做一些事情。

    【讨论】:

    • 啊哈,太好了。很简单。我已经做出了改变,知道为什么我的图片在点击时没有改变吗?
    【解决方案2】:

    不知道对类似情况有没有帮助:

    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')
    

    我不明白,但我花了很多时间来解决...... :-(

    【讨论】:

      【解决方案3】:
      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) ,则会产生错误。因此,对对象的显示要谨慎

      【讨论】:

        【解决方案4】:

        是的,我发现使用单线包装,例如 btt = Button(root,text='Hi Button').pack()

        一直在弄乱对象数据类型,例如将其设置为NoneType 但是如果你像这样使用.pack btt.pack() 这将缓解与 tkinter 相关的大多数问题。

        【讨论】:

          猜你喜欢
          • 2016-09-20
          • 2019-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-01
          • 2021-05-26
          • 2022-01-25
          • 2023-03-28
          相关资源
          最近更新 更多