簡體   English   中英

按鈕凹陷時更改顏色 Tkinter

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM