如何使用tkinter更改按钮颜色

15 投票
2 回答
123165 浏览
提问于 2025-04-16 15:04

我总是遇到以下错误:
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")

2 个回答

4

如果你想在改变按钮颜色的同时做其他操作,还有另一种方法。你可以使用 Tk().after 这个方法,并绑定一个改变颜色的函数,这样就可以同时改变颜色和执行其他操作。

Label.destroy 也是使用 after 方法的一个例子。

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

你还可以把颜色改回原来的样子。

19

当你写 self.button = Button(...).grid(...) 时,赋值给 self.button 的其实是 grid() 这个命令的结果,而不是你创建的 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)

撰写回答