gnikit / tkinter-tooltip

A ToolTip widget for tkinter
https://gnikit.github.io/tkinter-tooltip
MIT License
38 stars 3 forks source link

bind tooltip to another widget #43

Closed gnikit closed 1 year ago

gnikit commented 1 year ago

Seems like I got the idea wrong, I meant to add the ability to bind tooltips to other widgets, in my application I have a scrolling set of labels, and I want to add tooltips to all of them, but I can't bind the tooltips to the rest of the canvas to have it all scroll and be in the right place when I hover.

My code:

from tkinter import *
from tkinter import font
from tktooltip import ToolTip

root = Tk()
root.title('Font Families')
fonts=list(font.families())
fonts.sort()

text = "NV"

def populate(frame):
    for item in fonts:
        label = Label(frame,text=text,font=(item, 40)).pack()
        tip = ToolTip(label,msg=item)

def onFrameConfigure(canvas):
    canvas.configure(scrollregion=canvas.bbox("all"))

canvas = Canvas(root, borderwidth=0, background="#ffffff")
frame = Frame(canvas, background="#ffffff")
vsb = Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

def _on_mousewheel(event):
    canvas.yview_scroll(int(-1*(event.delta/120)), "units")

root.bind_all("<MouseWheel>", _on_mousewheel)

vsb.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=frame, anchor="nw")

frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

populate(frame)

root.mainloop()

as you can see, I can't bind the Tooltip, it gives the following error:

Traceback (most recent call last):
  File "e:\Karim\Media\Code\Font Viewer Tkinter\main.py", line 39, in <module>
    populate(frame)
  File "e:\Karim\Media\Code\Font Viewer Tkinter\main.py", line 16, in populate
    tip = ToolTip(label,msg=item)
  File "C:\Users\karim\AppData\Local\Programs\Python\Python310\lib\site-packages\tktooltip\tooltip.py", line 83, in __init__
    self.widget.bind("<Enter>", self.on_enter, add="+")
AttributeError: 'NoneType' object has no attribute 'bind'

Originally posted by @karimawii in https://github.com/gnikit/tkinter-tooltip/issues/19#issuecomment-1442082450

gnikit commented 1 year ago

@karimawii there is a bug in your sample code, calling .pack() to your Label and then assigning that to label will always be non since pack() returns None.

You should probably be doing something like

def populate(frame):
    for item in fonts:
        label = Label(frame,text=text,font=(item, 40))
        label.pack()
        tip = ToolTip(label,msg=item)