In this lesson we want to learn How to Create Tooltip in Tkinter, first of all let’s talk about Tkinter and Tooltip.
What is TKinter?
Tkinter is standard Python GUI library, TKinter is used for graphical user interfaces (GUIs). TKinter provides different widgets, you can use those widgets for building desktop applications. The name of Tkinter is taken from Tk interface, also TKinter is based on Tk GUI toolkit, and it is a graphical toolkit that is implemented in the Tcl scripting language.
What is Tooltip?
Tooltip is a graphical user interface element, tooltip provides additional information about a specific element when the user hovers their cursor over it. Tooltips are commonly used in software applications to offer brief contextual explanations or descriptions of UI elements such as buttons, icons or menu items.
How to Create Tooltip in Tkinter?
When you want to build tooltip in tkinter, then you need to do some more customization, because Tkinter doesn’t provide a built in tooltip widget. However, you can create a tooltip effect using a combination of event bindings and Toplevel windows.
This is a basic example of tkinter tooltip
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 40 41 42 |
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.show_tooltip) self.widget.bind("<Leave>", self.hide_tooltip) def show_tooltip(self, event): 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 = tk.Label(self.tooltip, text=self.text, bg="lightyellow", borderwidth=1, relief="solid") label.pack(ipadx=5, ipady=3) def hide_tooltip(self, event): if self.tooltip: self.tooltip.destroy() self.tooltip = None root = tk.Tk() root.title("Codeloo.org - TKinter Tooltip") # Set window icon root.iconphoto(True, tk.PhotoImage(file='codeloop.png')) button = tk.Button(root, text="Hover over me") button.pack(padx=20, pady=20) tooltip = Tooltip(button, "This is a tooltip") root.mainloop() |
In this example:
- We have defined a Tooltip class that takes a widget and text as arguments.
- We have binded <Enter> event to the widget to show the tooltip and <Leave> event to hide the tooltip.
- When the mouse enters the widget area, it calculates the position to display the tooltip relative to the widget.
- It creates a Toplevel window to display the tooltip with the specified text.
- When the mouse leaves the widget area, it destroys the tooltip window.
You can customize the appearance and behavior of the tooltip according to your needs by adjusting show_tooltip and hide_tooltip methods.
Run the code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email