简体   繁体   中英

Changing the colour of a Tkinter button in a function

I want to change the colour of a button when pressing a different button. The below code recreates the Attribrute Error.

Ideally the solution should be able to change all of the attributes of the button (see the attempted state change) but I didn't put this in the title because I don't know if 'attributes' is the right word.

import Tkinter

def tester():

    class window(Tkinter.Tk):
        def __init__(self,parent):
            Tkinter.Tk.__init__(self,parent)
            self.parent = parent
            self.initialize()

        def initialize(self):
            self.grid()
            button1 = Tkinter.Button(self,text=u"Button")
            button1.grid(padx=5,pady=5)

            button2 = Tkinter.Button(self,text=u"Change",command=self.colourer)
            button2.grid(column=1,row=0,pady=5)  

            button3 = Tkinter.Button(self,text=u"Disabled",state='disabled')
            button3.grid(column=1,row=0,pady=5)                     

        def colourer(self):
            self.button1.configure(bg='red')
#           self.button1.config(bg='red')  -- this gives same error
#           self.button3.configure(state='normal')  -- as does this
    if __name__ == "__main__":
        app = window(None)
        app.title('Tester')
        app.mainloop()

tester()

All of the ways suggested here give the same error: Changing colour of buttons in tkinter

Thanks

The root of your problem is that you're not defining self.button . You need to assign a value to that variable:

self.button = Tkinter.Button(...)
  1. you need give self.button1 while declaring
  2. if you see grid you gave same column name for button2 and button 3 so they overlap each other

try this

import Tkinter

def tester():

    class window(Tkinter.Tk):
        def __init__(self,parent):
            Tkinter.Tk.__init__(self,parent)
            self.parent = parent
            self.initialize()

        def initialize(self):
            print self.grid()
            self.button1 = Tkinter.Button(self,text=u"Button")
            self.button1.grid(padx=5,pady=5)

            self.button2 = Tkinter.Button(self,text=u"Change",command=self.colourer)
            self.button2.grid(column=1,row=0,pady=5)

            self.button3 = Tkinter.Button(self,text=u"Disabled",state='disabled')
            self.button3.grid(column=2,row=0,pady=5)



        def colourer(self):
            self.button1.configure(bg='red')
#           self.button1.config(bg='red')  -- this gives same error
#           self.button3.configure(state='normal')  -- as does this
    if __name__ == "__main__":
        app = window(None)
        app.title('Tester')
        app.mainloop()

tester()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM