0001 # general purpose 'tooltip' routines - currently unused in idlefork 0002 # (although the 'calltips' extension is partly based on this code) 0003 # may be useful for some purposes in (or almost in ;) the current project scope 0004 # Ideas gleaned from PySol 0005 0006 from Tkinter import * 0007 0008 class ToolTipBase: 0009 0010 def __init__(self, button): 0011 self.button = button 0012 self.tipwindow = None 0013 self.id = None 0014 self.x = self.y = 0 0015 self._id1 = self.button.bind("<Enter>", self.enter) 0016 self._id2 = self.button.bind("<Leave>", self.leave) 0017 self._id3 = self.button.bind("<ButtonPress>", self.leave) 0018 0019 def enter(self, event=None): 0020 self.schedule() 0021 0022 def leave(self, event=None): 0023 self.unschedule() 0024 self.hidetip() 0025 0026 def schedule(self): 0027 self.unschedule() 0028 self.id = self.button.after(1500, self.showtip) 0029 0030 def unschedule(self): 0031 id = self.id 0032 self.id = None 0033 if id: 0034 self.button.after_cancel(id) 0035 0036 def showtip(self): 0037 if self.tipwindow: 0038 return 0039 # The tip window must be completely outside the button; 0040 # otherwise when the mouse enters the tip window we get 0041 # a leave event and it disappears, and then we get an enter 0042 # event and it reappears, and so on forever :-( 0043 x = self.button.winfo_rootx() + 20 0044 y = self.button.winfo_rooty() + self.button.winfo_height() + 1 0045 self.tipwindow = tw = Toplevel(self.button) 0046 tw.wm_overrideredirect(1) 0047 tw.wm_geometry("+%d+%d" % (x, y)) 0048 self.showcontents() 0049 0050 def showcontents(self, text="Your text here"): 0051 # Override this in derived class 0052 label = Label(self.tipwindow, text=text, justify=LEFT, 0053 background="#ffffe0", relief=SOLID, borderwidth=1) 0054 label.pack() 0055 0056 def hidetip(self): 0057 tw = self.tipwindow 0058 self.tipwindow = None 0059 if tw: 0060 tw.destroy() 0061 0062 class ToolTip(ToolTipBase): 0063 def __init__(self, button, text): 0064 ToolTipBase.__init__(self, button) 0065 self.text = text 0066 def showcontents(self): 0067 ToolTipBase.showcontents(self, self.text) 0068 0069 class ListboxToolTip(ToolTipBase): 0070 def __init__(self, button, items): 0071 ToolTipBase.__init__(self, button) 0072 self.items = items 0073 def showcontents(self): 0074 listbox = Listbox(self.tipwindow, background="#ffffe0") 0075 listbox.pack() 0076 for item in self.items: 0077 listbox.insert(END, item) 0078 0079 def main(): 0080 # Test code 0081 root = Tk() 0082 b = Button(root, text="Hello", command=root.destroy) 0083 b.pack() 0084 root.update() 0085 tip = ListboxToolTip(b, ["Hello", "world"]) 0086 0087 # root.mainloop() # not in idle 0088 0089 main() 0090
Generated by PyXR 0.9.4