import tkinter as tk

class tkTooltip:
    def __init__(self, widget, text, bg = '#dcfbfe', fg = '#0000ff'):
        self.widget = widget
        self.text = text
        self.bg = bg
        self.fg = fg
        self.tipwindow = None

        # トリガーとなるイベントにコールバック関数を設定
        self.widget.bind('<Enter>', self.enter)
        self.widget.bind('<Leave>', self.leave)
        self.widget.bind("<Motion>", self.motion)

    def enter(self, event):
        self.showtip()
    
    def leave(self, event):
        self.hidetip()
    
    def motion(self, event):
#        self.hidetip()
#        self.showtip()
        pass

    def showtip(self):
        if self.tipwindow:
            self.tipwindow.destroy()

        self.tipwindow = tk.Toplevel(self.widget)
        self.tipwindow.wm_overrideredirect(True)

        self.label = tk.Label(self.tipwindow, text = self.text, justify = tk.LEFT, 
                                background = self.bg, foreground = self.fg, relief = tk.SOLID, borderwidth = 0)
        self.label.pack() #ipadx = 1)

        x, y, cx, cy = self.widget.bbox('insert')
        x += self.widget.winfo_rootx() + 25
        y += self.widget.winfo_rooty() + 20
        self.tipwindow.wm_geometry(f'+{x}+{y}')

        self.tipwindow.deiconify()
    
    def hidetip(self):
#        self.tipwindow.withdraw()
        if self.tipwindow:
            self.tipwindow.destroy()

def main():
    root = tk.Tk()

    label = tk.Label(root, text = 'Hover on the button')
    label.pack(pady = 50)

    tip = Tooltip(label, 'Button')

    root.mainloop()

if __name__ == "__main__":
    main()
