blob: 77d18c2f56cdf776862681048576fc569770d3a1 [file] [log] [blame]
Guido van Rossumd3a518b1999-06-01 18:19:02 +00001# Ideas gleaned from PySol
2
Guido van Rossumd3a518b1999-06-01 18:19:02 +00003from Tkinter import *
4
5class ToolTipBase:
6
7 def __init__(self, button):
8 self.button = button
9 self.tipwindow = None
10 self.id = None
11 self.x = self.y = 0
12 self._id1 = self.button.bind("<Enter>", self.enter)
13 self._id2 = self.button.bind("<Leave>", self.leave)
14 self._id3 = self.button.bind("<ButtonPress>", self.leave)
15
16 def enter(self, event=None):
17 self.schedule()
18
19 def leave(self, event=None):
20 self.unschedule()
21 self.hidetip()
22
23 def schedule(self):
24 self.unschedule()
25 self.id = self.button.after(1500, self.showtip)
26
27 def unschedule(self):
28 id = self.id
29 self.id = None
30 if id:
31 self.button.after_cancel(id)
32
33 def showtip(self):
34 if self.tipwindow:
35 return
36 # The tip window must be completely outside the button;
37 # otherwise when the mouse enters the tip window we get
38 # a leave event and it disappears, and then we get an enter
39 # event and it reappears, and so on forever :-(
40 x = self.button.winfo_rootx() + 20
41 y = self.button.winfo_rooty() + self.button.winfo_height() + 1
42 self.tipwindow = tw = Toplevel(self.button)
43 tw.wm_overrideredirect(1)
44 tw.wm_geometry("+%d+%d" % (x, y))
45 self.showcontents()
46
47 def showcontents(self, text="Your text here"):
48 # Override this in derived class
49 label = Label(self.tipwindow, text=text, justify=LEFT,
50 background="#ffffe0", relief=SOLID, borderwidth=1)
51 label.pack()
52
53 def hidetip(self):
54 tw = self.tipwindow
55 self.tipwindow = None
56 if tw:
57 tw.destroy()
58
59class ToolTip(ToolTipBase):
60 def __init__(self, button, text):
61 ToolTipBase.__init__(self, button)
62 self.text = text
63 def showcontents(self):
64 ToolTipBase.showcontents(self, self.text)
65
66class ListboxToolTip(ToolTipBase):
67 def __init__(self, button, items):
68 ToolTipBase.__init__(self, button)
69 self.items = items
70 def showcontents(self):
71 listbox = Listbox(self.tipwindow, background="#ffffe0")
72 listbox.pack()
73 for item in self.items:
74 listbox.insert(END, item)
75
76def main():
77 # Test code
78 root = Tk()
79 b = Button(root, text="Hello", command=root.destroy)
80 b.pack()
81 root.update()
82 tip = ListboxToolTip(b, ["Hello", "world"])
Tim Peters70c43782001-01-17 08:48:39 +000083
Guido van Rossumd3a518b1999-06-01 18:19:02 +000084 # root.mainloop() # not in idle
85
86main()