How do you add tool tips to buttons in guizero/tkinter?

Question:

I am trying to add tool tips into my Guizero app but I cant seem to combine them correctly. While I’m trying to minimize the amount of libraries I’m using if you can give me something else that works with Guizero that would be great too.

from tkinter import *
from tkinter.tix import *
from guizero import *
app=App(width=500,height=500)

#Create a tooltip
tip = Balloon(app)
app.add_tk_widget(Balloon)

#Create a Button widget
my_button=PushButton(app, text= "Hover Me")


#Bind the tooltip with button
tip.tk.bind_widget(my_button,balloonmsg="hovered text")

app.display()

Using tkinter with guizero

What I’m using

Asked By: PurpleLlama

||

Answers:

Have you looked into idlelib.tooltip? I know that works with tkinter, it might well work with guizero.

# quick and dirty example
import guizero as gz  # star imports are not your friend
from idlelib.tooltip import Hovertip

# skipping other imports and stuff for brevity...

my_button = gz.PushButton(app, text='Hover Me')  # button (note the 'gz' namespace)

tooltip = Hovertip(
    my_button.tk,  # the widget that gets the tooltip
    # edited to 'mybutton.tk' per acw1668 - thanks!
    'Super helpful tooltip text'
)

As I said, I’m not sure this will work with guizero out of the box, but it’s worth a shot.

UPDATE:
If you want to style the Hovertip, you can override the Hovertip class to include style attributes at __init__

from idlelib.tooltip import OnHoverTooltipBase  # import this instead of 'Hovertip'


# write your own 'Hovertip' class
class Hovertip(OnHoverTooltipBase):
    """Hovertip with custom styling"""
    def __init__(
        self,
        anchor_widget,
        text,
        hover_delay=1000,
        **kwargs,  # here's where you'll add your tk.Label keywords at init
    ):
        super(Hovertip, self).__init__(anchor_widget, hover_delay=hover_delay)
        self.text = text,
        self.kwargs = kwargs
    
    def showcontents(self):
        """Slightly modified to include **kwargs"""
        label = tk.Label(self.tipwindow, text=self.text, **self.kwargs)

Now when you initialize a new Hovertip, you can add parameter keywords to the tk.Label like so

tooltip = Hovertip(
    my_button.tk,
    'Super stylish tooltip text',
    # any keywords that apply to 'tk.Label' will work here!
    background='azure',  # named colors or '#BADA55' hex colors, as usual
    foreground='#123456',
    relief=tk.SOLID,
    borderwidth=2
)
Answered By: JRiggles