Tkinter - Button that changes its properties on hover

Tkinter - Button that changes its properties on hover

In Tkinter, you can make a button change its properties when it's hovered over by using event bindings. Specifically, you can bind the <Enter> event (when the mouse enters the widget) and the <Leave> event (when the mouse leaves the widget) to the button to change its properties.

Here's a simple example where a button will change its background color when hovered over and revert to its original color when the mouse is moved away:

import tkinter as tk def on_enter(event): """Function to run when the mouse enters the button""" event.widget['background'] = 'lightblue' # Change background color def on_leave(event): """Function to run when the mouse leaves the button""" event.widget['background'] = 'SystemButtonFace' # Change back to original color root = tk.Tk() root.geometry("200x200") # Create a button btn = tk.Button(root, text="Hover over me!") btn.pack(pady=50) # Bind the events to the button btn.bind("<Enter>", on_enter) btn.bind("<Leave>", on_leave) root.mainloop() 

In the above code:

  • The on_enter function changes the button's background color to lightblue when the mouse hovers over it.
  • The on_leave function reverts the button's background color to its default (SystemButtonFace) when the mouse is moved away.
  • The <Enter> and <Leave> events are bound to the button using the bind() method, so the specified functions are called when these events occur.

You can modify the properties in the on_enter and on_leave functions as per your requirements to achieve different visual effects when the button is hovered over.


More Tags

hyperledger-fabric runtimeexception subnet show max-path uipath data-structures mpdf r-faq resources

More Programming Guides

Other Guides

More Programming Examples