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