Search code examples
pythontkintertooltip

Display message when hovering over something with mouse cursor in Python


I have a GUI made with TKinter in Python. I would like to be able to display a message when my mouse cursor goes, for example, on top of a label or button. The purpose of this is to explain to the user what the button/label does or represents.

Is there a way to display text when hovering over a tkinter object in Python?


Solution

  • You need to set a binding on the <Enter> and <Leave> events.

    Note: if you choose to pop up a window (ie: a tooltip) make sure you don't pop it up directly under the mouse. What will happen is that it will cause a leave event to fire because the cursor leaves the label and enters the popup. Then, your leave handler will dismiss the window, your cursor will enter the label, which causes an enter event, which pops up the window, which causes a leave event, which dismisses the window, which causes an enter event, ... ad infinitum.

    For simplicity, here's an example that updates a label, similar to a statusbar that some apps use. Creating a tooltip or some other way of displaying the information still starts with the same core technique of binding to <Enter> and <Leave>.

    import Tkinter as tk
    
    class Example(tk.Frame):
        def __init__(self, *args, **kwargs):
            tk.Frame.__init__(self, *args, **kwargs)
            self.l1 = tk.Label(self, text="Hover over me")
            self.l2 = tk.Label(self, text="", width=40)
            self.l1.pack(side="top")
            self.l2.pack(side="top", fill="x")
    
            self.l1.bind("<Enter>", self.on_enter)
            self.l1.bind("<Leave>", self.on_leave)
    
        def on_enter(self, event):
            self.l2.configure(text="Hello world")
    
        def on_leave(self, enter):
            self.l2.configure(text="")
    
    if __name__ == "__main__":
        root = tk.Tk()
        Example(root).pack(side="top", fill="both", expand="true")
        root.mainloop()