简体   繁体   中英

Change color when button is sunken Tkinter

How could I make it, so when any button in my program is sunken (so being clicked) that button gets a certain background color (white) for 1 sec.

I was thinking of something like this:

Whenever ButtonClicked = Sunken, ButtonClicked['bg'] = 'white' for 1 sec

But I have lots of buttons, and every button has a different function. So what is an easy to implement program so this happens to all buttons?

The simplest solution is to create your own custom button class, and add the behavior to that class.

You can use after to arrange for the color to be restored after some amount of time.

For example:

class CustomButton(tk.Button):
    def __init__(self, *args, **kwargs):
        self.altcolor = kwargs.pop("altcolor", "pink")
        tk.Button.__init__(self, *args, **kwargs)
        self.bind("<ButtonPress>", self.twinkle)

    def twinkle(self, event):
        # get the current activebackground...
        bg = self.cget("activebackground")

        # change it ...
        self.configure(activebackground=self.altcolor)

        # and then restore it after a second
        self.after(1000, lambda: self.configure(activebackground=bg))

You would use it like you would any other Button . It takes one new argument, altcolor , which is the extra color you want to use:

b1 = CustomButton(root, text="Click me!", altcolor="pink")
b2 = CustomButton(root, text="No, Click me!", altcolor="blue")

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