In this tutorial, we will learn how to add functionality when you hover over any widget in the Python Tkinter framework. Adding functionality when you hover is a very good practice because it enhances the user experience and makes the frontend part more interactive.
Running any function on Hover in Tkinter
Let’s start simple. Suppose we take two inputs of numbers and want to multiply them and display the product on the window. To implement any functionality in the code, I suggest you write down the approach first.
- First, we need the function that accepts the two numbers from users, then calculates the product and displays the result on the window.
- Now, we need to write the function
on_hover()
which will call the function to calculate the product. - By this step, we have written all the functions, and now our work is to display on the
tkinter
framework. Createentry
widgets in which the user will input the numbers. Also, create thelabel
widget where the result will be displayed. - Now, create the
button
widget and, using the.bind()
function, bind theon_hover()
function to the button when we hover on it. “<Enter>” is passed as we want to call the function when the cursor enters the button region.
import tkinter as tk def multiply_numbers(): try: num1 = float(entry1.get()) num2 = float(entry2.get()) result = num1 * num2 result_label.config(text=f"Result: {result}") except ValueError: result_label.config(text="Invalid input. Please enter valid numbers.") def on_hover(event): multiply_numbers() root = tk.Tk() root.title("Multiplication on Hovering") root.geometry("400x300") # Create entry widgets for user input entry1 = tk.Entry(root, width=10) entry2 = tk.Entry(root, width=10) button = tk.Button(root, text="Multiply", command=multiply_numbers) # Label to display the result result_label = tk.Label(root, text="Result: ") entry1.pack(side="top", padx=5, pady=5) entry2.pack(side="top", padx=5, pady=5) button.pack(side="top", pady=10) result_label.pack(side="top") button.bind("<Enter>", on_hover) root.mainloop()
Output
Adding tooltip
You have seen on various websites that when you hover over some elements, a dialogue box containing additional useful information about that particular element opens up. This feature is called Tooltip. It is usually kept so the user won’t get stuck on any part. Let’s learn how to add the tooltip.
I am defining a class for the tooltip feature as it will be easier to bind all the functions and utilize the concept of OOPs.
import tkinter as tk from tkinter import ttk class Tooltip: def __init__(self, widget, text): self.widget = widget self.text = text self.tooltip = None self.widget.bind("<Enter>", self.show) self.widget.bind("<Leave>", self.hide) def show(self, event=None): x, y, _, _ = self.widget.bbox("insert") x += self.widget.winfo_rootx() + 25 y += self.widget.winfo_rooty() + 25 self.tooltip = tk.Toplevel(self.widget) self.tooltip.wm_overrideredirect(True) self.tooltip.wm_geometry(f"+{x}+{y}") label = ttk.Label(self.tooltip, text=self.text, background="#ffffe0", relief="solid", borderwidth=1) label.pack() def hide(self, event=None): if self.tooltip: self.tooltip.destroy() self.tooltip = None root = tk.Tk() root.title("Tooltip Example") root.geometry("400x300") button = ttk.Button(root, text="Click me!") button.pack() tooltip = Tooltip(button, "This is a tooltip") root.mainloop()
Code Explanation
- First, we are initializing the
constructor
of the class where we are binding the functions of ‘Enter’ and ‘Leave.’ This refers to the mouse’s cursor entering the area of a given element and leaving it. - Now, create a
show()
function for displaying the tooltip. We have to calculate the location of the tooltip and store the coordinates in x and y. I am calculating the location based on the widget size on which the tooltip will be applied. Then, using the.wm_geometry()
function, we are setting the location of the tooltip. - Add the
label
widget with a tooltip and modify the parameters such as background color and border width. - Write the
hide()
function to hide the tooltip when the cursor leaves that widget. - I am creating the button using the
ttk.Button
on which I will add the tooltip. - Write the tip in the brackets and pass it when initializing the class.