How to display tooltips in tkinter?

Member

by kadin , in category: Third Party Scripts , a month ago

How to display tooltips in tkinter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a month ago

@kadin 

To display tooltips in tkinter, you can use the createToolTip function provided below. This function creates a tooltip and binds it to a widget when the user hovers over it.


Here is the createToolTip function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import tkinter as tk

class ToolTip:
    def __init__(self, widget, text):
        self.widget = widget
        self.text = text
        self.tooltip = None

        self.widget.bind("<Enter>", self.on_enter)
        self.widget.bind("<Leave>", self.on_leave)

    def on_enter(self, event):
        x = y = 0
        x, y, _, _ = self.widget.bbox("insert")
        x += self.widget.winfo_rootx() + 25
        y += self.widget.winfo_rooty() + 20

        self.tooltip = tk.Toplevel(self.widget)
        self.tooltip.wm_overrideredirect(True)
        self.tooltip.wm_geometry("+%d+%d" % (x, y))

        label = tk.Label(self.tooltip, text=self.text, bg='yellow', relief='solid', borderwidth=1)
        label.pack(ipadx=1)

    def on_leave(self, event):
        if self.tooltip:
            self.tooltip.destroy()

def createToolTip(widget, text):
    tooltip = ToolTip(widget, text)
    return tooltip

# Example usage
root = tk.Tk()
button = tk.Button(root, text="Hover over me")
button.pack()
createToolTip(button, "This is a tooltip")

root.mainloop()


In this code:

  • We define the ToolTip class that creates a tooltip when the user hovers over a widget.
  • The createToolTip function creates an instance of the ToolTip class and binds it to a widget.
  • We create a simple example in which a tooltip is displayed when hovering over a button.


You can modify the appearance of the tooltip by changing the background color, border width, text size, etc., in the on_enter method of the ToolTip class.