按钮凹陷时改变颜色Tkinter

时间:2016-10-13 14:29:00

标签: python button tkinter click

我怎么能这样做,所以当我的程序中的任何按钮凹陷(因此被点击)时,该按钮会获得一定的背景颜色(白色),持续1秒。

我在考虑这样的事情:

每当ButtonClicked =沉没时,ButtonClicked ['bg'] ='白色'持续1秒

但我有很多按钮,每个按钮都有不同的功能。那么什么是一个易于实现的程序,所以这会发生在所有按钮上?

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是创建自己的自定义按钮类,并将行为添加到该类。

您可以使用after来安排在一段时间后恢复颜色。

例如:

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))

您可以像使用任何其他Button一样使用它。它需要一个新的参数altcolor,这是你想要使用的额外颜色:

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