Tkinter悬停在按钮上 - >颜色变化

时间:2018-04-17 22:50:42

标签: python tkinter hover

是否有可能在悬停在Button之后更改 class AddUserIdToCard < ActiveRecord::Migration[5.0] def change add_reference :cards, :users, foreign_key: true end end 的背景颜色? Tkinter的代码是什么?

1 个答案:

答案 0 :(得分:4)

可悲的是,当您点击按钮而不是将鼠标悬停在按钮上时,activebackgroundactiveforeground选项似乎才有效。请改用<Leave><Enter>事件

import tkinter as tk

def on_enter(e):
    myButton['background'] = 'green'

def on_leave(e):
    myButton['background'] = 'SystemButtonFace'

root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()


myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)

root.mainloop()

为多个按钮执行此操作的一种更简单的方法是创建一个新的Button类,修改默认按钮的行为,以便在您悬停时activebackground实际工作。

import tkinter as tk

class HoverButton(tk.Button):
    def __init__(self, master, **kw):
        tk.Button.__init__(self,master=master,**kw)
        self.defaultBackground = self["background"]
        self.bind("<Enter>", self.on_enter)
        self.bind("<Leave>", self.on_leave)

    def on_enter(self, e):
        self['background'] = self['activebackground']

    def on_leave(self, e):
        self['background'] = self.defaultBackground

root = tk.Tk()

classButton = HoverButton(root,text="Classy Button", activebackground='green')
classButton.grid()

root.mainloop()