1#!/usr/local/bin/python3.8
2'''Michael Lange <klappnase (at) freakmail (dot) de>
3The ToolTip class provides a flexible tooltip widget for tkinter; it is based on IDLE's ToolTip
4module which unfortunately seems to be broken (at least the version I saw).
5INITIALIZATION OPTIONS:
6anchor :        where the text should be positioned inside the widget, must be on of "n", "s", "e", "w", "nw" and so on;
7                default is "center"
8bd :            borderwidth of the widget; default is 1 (NOTE: don't use "borderwidth" here)
9bg :            background color to use for the widget; default is "lightyellow" (NOTE: don't use "background")
10delay :         time in ms that it takes for the widget to appear on the screen when the mouse pointer has
11                entered the parent widget; default is 1500
12fg :            foreground (i.e. text) color to use; default is "black" (NOTE: don't use "foreground")
13follow_mouse :  if set to 1 the tooltip will follow the mouse pointer instead of being displayed
14                outside of the parent widget; this may be useful if you want to use tooltips for
15                large widgets like listboxes or canvases; default is 0
16font :          font to use for the widget; default is system specific
17justify :       how multiple lines of text will be aligned, must be "left", "right" or "center"; default is "left"
18padx :          extra space added to the left and right within the widget; default is 4
19pady :          extra space above and below the text; default is 2
20relief :        one of "flat", "ridge", "groove", "raised", "sunken" or "solid"; default is "solid"
21state :         must be "normal" or "disabled"; if set to "disabled" the tooltip will not appear; default is "normal"
22text :          the text that is displayed inside the widget
23textvariable :  if set to an instance of tkinter.StringVar() the variable's value will be used as text for the widget
24width :         width of the widget; the default is 0, which means that "wraplength" will be used to limit the widgets width
25wraplength :    limits the number of characters in each line; default is 150
26
27WIDGET METHODS:
28configure(**opts) : change one or more of the widget's options as described above; the changes will take effect the
29                    next time the tooltip shows up; NOTE: follow_mouse cannot be changed after widget initialization
30
31Other widget methods that might be useful if you want to subclass ToolTip:
32enter() :           callback when the mouse pointer enters the parent widget
33leave() :           called when the mouse pointer leaves the parent widget
34motion() :          is called when the mouse pointer moves inside the parent widget if follow_mouse is set to 1 and the
35                    tooltip has shown up to continually update the coordinates of the tooltip window
36coords() :          calculates the screen coordinates of the tooltip window
37create_contents() : creates the contents of the tooltip window (by default a tkinter.Label)
38'''
39# Ideas gleaned from PySol
40
41import tkinter
42
43class ToolTip:
44    def __init__(self, master, text='Your text here', delay=1500, **opts):
45        self.master = master
46        self._opts = {'anchor':'center', 'bd':1, 'bg':'lightyellow', 'delay':delay, 'fg':'black',\
47                      'follow_mouse':0, 'font':None, 'justify':'left', 'padx':4, 'pady':2,\
48                      'relief':'solid', 'state':'normal', 'text':text, 'textvariable':None,\
49                      'width':0, 'wraplength':150}
50        self.configure(**opts)
51        self._tipwindow = None
52        self._id = None
53        self._id1 = self.master.bind("<Enter>", self.enter, '+')
54        self._id2 = self.master.bind("<Leave>", self.leave, '+')
55        self._id3 = self.master.bind("<ButtonPress>", self.leave, '+')
56        self._follow_mouse = 0
57        if self._opts['follow_mouse']:
58            self._id4 = self.master.bind("<Motion>", self.motion, '+')
59            self._follow_mouse = 1
60
61    def configure(self, **opts):
62        for key in opts:
63            if key in self._opts:
64                self._opts[key] = opts[key]
65            else:
66                KeyError = 'KeyError: Unknown option: "%s"' %key
67                raise KeyError
68
69    ##----these methods handle the callbacks on "<Enter>", "<Leave>" and "<Motion>"---------------##
70    ##----events on the parent widget; override them if you want to change the widget's behavior--##
71
72    def enter(self, event=None):
73        self._schedule()
74
75    def leave(self, event=None):
76        self._unschedule()
77        self._hide()
78
79    def motion(self, event=None):
80        if self._tipwindow and self._follow_mouse:
81            x, y = self.coords()
82            self._tipwindow.wm_geometry("+%d+%d" % (x, y))
83
84    ##------the methods that do the work:---------------------------------------------------------##
85
86    def _schedule(self):
87        self._unschedule()
88        if self._opts['state'] == 'disabled':
89            return
90        self._id = self.master.after(self._opts['delay'], self._show)
91
92    def _unschedule(self):
93        id = self._id
94        self._id = None
95        if id:
96            self.master.after_cancel(id)
97
98    def _show(self):
99        if self._opts['state'] == 'disabled':
100            self._unschedule()
101            return
102        if not self._tipwindow:
103            self._tipwindow = tw = tkinter.Toplevel(self.master)
104            # hide the window until we know the geometry
105            tw.withdraw()
106            tw.wm_overrideredirect(1)
107
108            if tw.tk.call("tk", "windowingsystem") == 'aqua':
109                tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "none")
110
111            self.create_contents()
112            tw.update_idletasks()
113            x, y = self.coords()
114            tw.wm_geometry("+%d+%d" % (x, y))
115            tw.deiconify()
116            tw.lift()
117
118    def _hide(self):
119        tw = self._tipwindow
120        self._tipwindow = None
121        if tw:
122            tw.destroy()
123
124    ##----these methods might be overridden in derived classes:----------------------------------##
125
126    def coords(self):
127        # The tip window must be completely outside the master widget;
128        # otherwise when the mouse enters the tip window we get
129        # a leave event and it disappears, and then we get an enter
130        # event and it reappears, and so on forever :-(
131        # or we take care that the mouse pointer is always outside the tipwindow :-)
132        tw = self._tipwindow
133        twx, twy = tw.winfo_reqwidth(), tw.winfo_reqheight()
134        w, h = tw.winfo_screenwidth(), tw.winfo_screenheight()
135        # calculate the y coordinate:
136        if self._follow_mouse:
137            y = tw.winfo_pointery() + 20
138            # make sure the tipwindow is never outside the screen:
139            if y + twy > h:
140                y = y - twy - 30
141        else:
142            y = self.master.winfo_rooty() + self.master.winfo_height() + 3
143            if y + twy > h:
144                y = self.master.winfo_rooty() - twy - 3
145        # we can use the same x coord in both cases:
146        x = tw.winfo_pointerx() - twx / 2
147        if x < 0:
148            x = 0
149        elif x + twx > w:
150            x = w - twx
151        return x, y
152
153    def create_contents(self):
154        opts = self._opts.copy()
155        for opt in ('delay', 'follow_mouse', 'state'):
156            del opts[opt]
157        label = tkinter.Label(self._tipwindow, **opts)
158        label.pack()
159