如何使用tkinter更改按钮颜色

Pau*_*jak 10 python tkinter button

我一直收到以下错误:AttributeError:'NoneType'对象没有属性'configure'

# create color button
self.button = Button(self,
                     text = "Click Me",
                     command = self.color_change,
                     bg = "blue"
                    ).grid(row = 2, column = 2, sticky = W)

def color_change(self):
    """Changes the button's color"""

    self.button.configure(bg = "red")
Run Code Online (Sandbox Code Playgroud)

Sym*_*mon 16

执行此操作时self.button = Button(...).grid(...),分配的内容self.buttongrid()命令的结果,而不是Button创建的对象的引用.

您需要self.button在打包/编制变量之前分配变量.它应该看起来像这样:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
Run Code Online (Sandbox Code Playgroud)

  • 一旦你已经按下按钮,你如何改变背景? (4认同)