[英]Change color when button is sunken Tkinter
我怎么能做到,所以当我的程序中的任何按钮下沉(因此被点击)时,该按钮会在 1 秒内获得某种背景颜色(白色)。
我在想这样的事情:
每当 ButtonClicked = Sunken,ButtonClicked['bg'] = 'white' 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.