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("", self.on_enter) self.bind(" ", 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()
Here is what the above code is Doing:
1. We create a class called HoverButton.
2. We create a constructor for that class.
3. We create a method called on_enter.
4. We create a method called on_leave.
5. We bind the on_enter method to the
6. We bind the on_leave method to the
7. We create an instance of HoverButton.
8. We call the grid method on our instance.
9. We enter the main loop of the GUI.