Skip to content

Instantly share code, notes, and snippets.

@fladd
Created April 11, 2021 20:43
Show Gist options
  • Save fladd/09ae787df104699597017d0bf8b7b9ad to your computer and use it in GitHub Desktop.
Save fladd/09ae787df104699597017d0bf8b7b9ad to your computer and use it in GitHub Desktop.
class TreeviewTooltip:
def __init__(self, treeview, texts=[]):
self._treeview = treeview
self._texts = texts
self._tooltip_window = None
self._tooltip_x = self.tooltip_y = 0
self._last_idd = self._last_col = None
self._waittime = 500
self._id = None
self._style = ttk.Style()
self._treeview.bind("<Motion>", self.schedule)
@property
def treeview(self):
return self._treeview
@property
def texts(self):
return self._texts
@texts.setter
def texts(self, value):
self._texts = value
def schedule(self, event):
self.unschedule()
idd = self._treeview.identify_row(event.y)
col = self._treeview.identify_column(event.x)
if not idd or not self._texts[int(idd)][int(col.strip("#"))-1]:
if self._tooltip_window:
self.hide()
return
if idd == self._last_idd and col == self._last_col:
return
if self._tooltip_window:
self.hide()
self._id = self._treeview.after(self._waittime, lambda: self.show(event))
def unschedule(self):
id = self._id
self._id = None
if id:
self._treeview.after_cancel(id)
def show(self, event):
idd = self._treeview.identify_row(event.y)
col = self._treeview.identify_column(event.x)
#x, y, cx, cy = self.bbox("insert")
x, y, cx, cy = self._treeview.bbox(idd, column=col)
#x = event.x
x = x + self._treeview.winfo_rootx() + 1
y = y + cy + self._treeview.winfo_rooty() #+ 20#- 3# + 20
width = self._treeview.column(f'{int(col.strip("#"))-1}')['width']
height = self._style.lookup("Treeview", "rowheight")
self._tooltip_window = tk.Toplevel(self._treeview)
self._tooltip_window.wm_overrideredirect(1)
self._tooltip_window.wm_geometry(f"+{x}+{y}")
try:
# For Mac OS
self._tooltip_window.tk.call("::tk::unsupported::MacWindowStyle",
"style", self._tooltip_window._w,
"help", "noActivates")
except tk.TclError:
pass
if self._treeview.tag_has("bold", idd):
weight="bold"
else:
weight="normal"
label = tk.Label(self._tooltip_window,
text=self._texts[int(idd)][int(col.strip("#"))-1],
justify=tk.LEFT, background="#ffffe0",
relief=tk.SOLID, borderwidth=1,
font=(FONTNAME, "13", weight),
wraplength=width)
label.grid(ipadx=1, ipady=2, sticky="n")
self._last_idd = idd
self._last_col = col
def hide(self):
if self._tooltip_window:
self._tooltip_window.destroy()
self._tooltip_window = None
self._last_idd = self._last_col = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment