I'm adding tooltips to my program, they should appear if mouse is on the widget more than 1 seconds. But there is a problem that tooltip always appears when mouse simply passes over the widget. I mean they should appear if mouse remains on the widget more than 1 seconds but they also appear when mouse doesn't remains on the widget.
So I decided to add some lines to code that delays 1 seconds when mouse enters the widget and checks if mouse is still on the widget. If mouse is still there, then makes tooltip appear. But I don't know how to check if mouse is on a widget. I've tried widget.focus_get()
but it simply gives a dot for output. Which is also gives a dot if mouse wasn't there. So this is useless for me. I've done lot's of research but I wasn't able to find something about this.
I am using Python 3.7.9 and tkinter.ttk
I was copied the code from here and modified a little bit to fade-in and fade-out animations. Here is my code:
label = Label(root, text="Label")
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text, widget):
global tw
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 20
y = y + cy + self.widget.winfo_rooty() +20
self.tipwindow = tw = Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
tw.attributes("-alpha", 0)
label = Label(tw, text=self.text, justify=LEFT, relief=SOLID, borderwidth=1)
label.pack(ipadx=1)
def fade_in():
alpha = tw.attributes("-alpha")
if alpha < root.attributes("-alpha"):
alpha += .1
tw.attributes("-alpha", alpha)
tw.after(10, fade_in)
elif alpha == root.attributes("-alpha"):
tw.attributes("-alpha", root.attributes("-alpha"))
try:
tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates")
except TclError:
pass
fade_in()
def hidetip(self, widget):
tw = self.tipwindow
self.tipwindow = None
def fade_away():
alpha = tw.attributes("-alpha")
if alpha > 0:
alpha -= .1
tw.attributes("-alpha", alpha)
tw.after(10, fade_away)
else:
tw.destroy()
fade_away()
def createToolTip(widget, text):
toolTip = ToolTip(widget)
def enter(event):
time.sleep(1000) #Wait 1 second
if widget.focus_get() == True: #Check if mouse is still on the widget. But not working.
toolTip.showtip(text, widget)
def leave(event):
ToolTipActive = False
toolTip.hidetip(widget)
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
createToolTip(label, "This is a tooltip")