Tkinter Button bind hover message

This is the hover message (tooltip-style) behavior into a reusable class is the right way to go.

python 复制代码
import tkinter as tk

class HoverTooltip:
    """A reusable tooltip class for Tkinter widgets."""

    def __init__(self, widget, text, offset=(10, 10)):
        self.widget = widget
        self.text = text
        self.offset = offset
        self.tooltip = None

        # Bind hover events
        widget.bind("<Enter>", self.show_tooltip)
        widget.bind("<Leave>", self.hide_tooltip)
        widget.bind("<Motion>", self.move_tooltip)

    def show_tooltip(self, event):
        """Display the tooltip near the cursor."""
        if self.tooltip or not self.text:
            return

        self.tooltip = tk.Toplevel(self.widget)
        self.tooltip.wm_overrideredirect(True)  # no window borders
        self.tooltip.attributes("-topmost", True)

        label = tk.Label(
            self.tooltip,
            text=self.text,
            bg="yellow",
            relief="solid",
            borderwidth=1,
            padx=5,
            pady=2,
        )
        label.pack(ipadx=1)

        # Position the tooltip initially
        self.move_tooltip(event)

    def move_tooltip(self, event):
        """Update tooltip position as the cursor moves."""
        if self.tooltip:
            x = event.x_root + self.offset[0]
            y = event.y_root + self.offset[1]
            self.tooltip.geometry(f"+{x}+{y}")

    def hide_tooltip(self, event):
        """Destroy the tooltip when cursor leaves."""
        if self.tooltip:
            self.tooltip.destroy()
            self.tooltip = None


# --- Example usage ---
if __name__ == "__main__":
    root = tk.Tk()
    root.title("Hover Tooltip Class Example")

    btn1 = tk.Button(root, text="Hover Me 1")
    btn1.pack(pady=10)

    btn2 = tk.Button(root, text="Hover Me 2")
    btn2.pack(pady=10)

    HoverTooltip(btn1, "This is the first button tooltip!")
    HoverTooltip(btn2, "Another helpful message here!")

    root.mainloop()

Another simple way

python 复制代码
# Import the tkinter library
from tkinter import *
from tkinter.tix import *

# Create an instance of tkinter frame
win = Tk()
# Set the geometry
win.geometry("400x200")

# Create a tooltip
tip = Balloon(win)

# Create a Button widget
my_button = Button(win, text="Python", font=('Helvetica bold', 20))
my_button.pack(pady=20)

# Bind the tooltip with button
tip.bind_widget(my_button, balloonmsg="Python is an interpreted, high-level and general-purpose programming language")

win.mainloop()
相关推荐
会Tk矩阵群控的小木5 分钟前
基于Python的iMessage短信群发与社媒多账号统一管理系统实现
开发语言·windows·python·新媒体运营·开源软件·个人开发
我是一颗柠檬8 分钟前
【Java项目技术亮点】分库分表+数据路由策略:单表5000万后的架构升级方案
java·开发语言·分布式·架构
wu_ye_m10 分钟前
学习c语言第35天 函数声明和定义
c语言·开发语言·学习
njsgcs18 分钟前
c# solidworks 创建装配体工程图+bom
开发语言·c#·solidworks
质造者32 分钟前
LangChain + Ollama + Tavily 实现旅游问答系统
linux·人工智能·python·langchain·rag
小林敲代码778837 分钟前
记录一下IDEA中很多变量变色的方案
java·开发语言·spring boot·idea
伊布拉西莫44 分钟前
【流畅的Python】第20章:并发执行器 — 学习笔记
笔记·python·学习
njsgcs1 小时前
c# solidworks 工程图获得展开视图不在固定面螺纹特征的位置
开发语言·c#·solidworks
IT策士1 小时前
Redis 从入门到精通:Python 操作 Redis
redis·python·bootstrap
编码者卢布1 小时前
【Azure AI Search】 searchMode=any 和 searchMode=all 有什么区别?
人工智能·python·flask