将鼠标悬停在tkinter上时更改按钮颜色

时间:2016-02-15 14:46:24

标签: python tkinter hover bind

当我用光标悬停在按钮上时,我试图制作一个带有按钮的小部件。使用我在互联网上找到的代码,我试图编写一个可以做到这一点的小型测试程序。我希望能够在我单击鼠标左键时激活颜色切换,并在我右键单击时将其停用。我可以激活它,但是当我右键单击时它不会停用。

import tkinter

class App:
    def __init__(self, root):
        self.root = root
        self.mouse_pressed = False
        self.root.bind("<ButtonPress-1>", self.OnMouseDown)
        self.root.bind("<ButtonRelease-3>", self.OnMouseUp)

        self.Hover1 = tkinter.Button(root,text="Red color", bg="SystemButtonFace")
        self.Hover1.pack()

        self.Hover2 = tkinter.Button(root,text="Yellow color", bg="SystemButtonFace")
        self.Hover2.pack()



    def do_work(self):
        if self.mouse_pressed:
            self.Hover1.bind("<Enter>", lambda event, h=self.Hover1: h.configure(bg="red"))
            self.Hover1.bind("<Leave>", lambda event, h=self.Hover1: h.configure(bg="SystemButtonFace"))

            self.Hover2.bind("<Enter>", lambda event, h=self.Hover2: h.configure(bg="yellow"))
            self.Hover2.bind("<Leave>", lambda event, h=self.Hover2: h.configure(bg="SystemButtonFace"))

    def OnMouseDown(self, event):
        self.mouse_pressed = True
        self.do_work()

    def OnMouseUp(self, event):
        self.mouse_pressed = False
        self.do_work()

root=tkinter.Tk()
app = App(root)
root.mainloop()

如何停用它以使颜色停止变化?还有可能使它只有在按下鼠标左键时才有效吗?

2 个答案:

答案 0 :(得分:3)

do_work()mouse_pressed时,您的False方法无效。您应该在False时添加一些功能。

def do_work(self):
    if self.mouse_pressed:
            ...
    else: 
        #unbind events from both buttons
        self.Hover1.unbind("<Enter>")
        self.Hover1.unbind("<Leave>")

        self.Hover2.unbind("<Enter>")
        self.Hover2.unbind("<Leave>")

        #return their color to original state
        self.Hover1.configure(bg="SystemButtonFace")
        self.Hover2.configure(bg="SystemButtonFace")

答案 1 :(得分:2)

它未被停用,因为按钮仍然绑定到事件,因此您需要取消绑定它们。试试这个:

    def do_work(self):
        if self.mouse_pressed:
            self.Hover1.bind("<Enter>", lambda event, h=self.Hover1: h.configure(bg="red"))
            self.Hover1.bind("<Leave>", lambda event, h=self.Hover1: h.configure(bg="SystemButtonFace"))

            self.Hover2.bind("<Enter>", lambda event, h=self.Hover2: h.configure(bg="yellow"))
            self.Hover2.bind("<Leave>", lambda event, h=self.Hover2: h.configure(bg="SystemButtonFace"))
        else:
            self.Hover1.unbind("<Enter>")
            self.Hover1.unbind("<Leave>")
            self.Hover2.unbind("<Enter>")
            self.Hover2.unbind("<Leave>")