Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button color with tkinter [duplicate]

I keep getting the following error: AttributeError: 'NoneType' object has no attribute '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")
like image 657
Paul Ronjak Avatar asked Apr 04 '11 20:04

Paul Ronjak


2 Answers

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    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)

You can also revert to the original color.

like image 172
technazi Avatar answered Sep 28 '22 04:09

technazi


When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)
like image 33
Symon Avatar answered Sep 28 '22 04:09

Symon