Tkinter Hovering Over Button -> Color Change
Solution 1:
Sadly the activebackground
and activeforeground
options only seem to work when you are clicking on the button rather than when you hover over the button. Use the <Leave>
and <Enter>
events instead
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()
As pointed out in the comments, if we want multiple buttons, we can bind the buttons to functions that use the event data for the click event to change the background of the button.
import tkinter as tk
def on_enter(e):
e.widget['background'] = 'green'
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
myButton2 = tk.Button(root,text="Click Me")
myButton2.grid()
myButton2.bind("<Enter>", on_enter)
myButton2.bind("<Leave>", on_leave)
root.mainloop()
A slicker way to do it for multiple buttons would be to create a new Button class that modifies the behaviour of the default button so that the activebackground
actually works when you hover.
import tkinter as tk
classHoverButton(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)
defon_enter(self, e):
self['background'] = self['activebackground']
defon_leave(self, e):
self['background'] = self.defaultBackground
root = tk.Tk()
classButton = HoverButton(root,text="Classy Button", activebackground='green')
classButton.grid()
root.mainloop()
Solution 2:
Plain and simple
In your Button
object properties you have the tags: activebackground
& activeforeground
that are activated whenever there is interaction with the instace created. That is: the button object you've created.
e.g.
from tkinter import *
root = Tk()
button = Button(root, text="Click me", bg="#000", fg="#fff", activebackground="#f00", activeforeground="#fff")
button.pack()
root.mainloop()
Post a Comment for "Tkinter Hovering Over Button -> Color Change"