Welcome, guest | Sign In | My Account | Store | Cart

This is an extension for the Button class of Tkinter. This class creates a tip-window when the mouse is entering a button widget.

Python, 66 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/python
from Tkinter import *

tipDelay = 1000


class TipButton(Button):
    def __init__(self,parent=None,tip='',**kw):
        Button.__init__(self,parent,kw)
        self.bind('<Enter>',self._delayedshow)
        self.bind('<Button-1>',self._leave)
        self.bind('<Leave>',self._leave)

        self.frame = Toplevel(self,bd=1,bg="black")
        self.frame.withdraw()
        self.frame.overrideredirect(1)
        self.frame.transient()     
        l=Label(self.frame,text=tip,bg="yellow",justify='left')
	l.update_idletasks()
        l.pack()
	l.update_idletasks()
        self.tipwidth = l.winfo_width()
        self.tipheight = l.winfo_height()

    def _delayedshow(self,event):
        self.focus_set()
        self.request=self.after(tipDelay,self._show)


    def _show(self):
        self.update_idletasks()
        FixX = self.winfo_rootx()+self.winfo_width()
        FixY = self.winfo_rooty()+self.winfo_height()
        if FixX + self.tipwidth > self.winfo_screenwidth():
            FixX = FixX-self.winfo_width()-self.tipwidth
        if FixY + self.tipheight > self.winfo_screenheight():
            FixY = FixY-self.winfo_height()-self.tipheight
        self.frame.geometry('+%d+%d'%(FixX,FixY))
        self.frame.deiconify()
#       print self.frame.geometry()
#	print self.winfo_screenwidth()

        
    def _leave(self,event):
        self.frame.withdraw()
        self.after_cancel(self.request)


#--- testing ---

if __name__ == '__main__':
    def log(a):
        print a

    main = Tk()
    b1 = TipButton(main,"tip1",text="Example1",\
                  command=(lambda e="tip1": log(e)))
    b2 = TipButton(main,"tip2",text="Example2",\
                  command=(lambda e="tip2": log(e)))
    b1.pack()
    b2.pack()


    main.mainloop()

### end module ###

For the behaviour of this widget is considered that the tip will be visible again when the widget will be moved to the bottom/right border of the screen.

A more generic design would be to incorporate the following features: - the tip delay as part of the constructor - the foreground/background color of the tip-window as part of the constructor - disabeling the tip when an empty tip-string is given to the constructor

This should be simple to deal.

Created by Frank Jeworrek-Schmidt on Thu, 3 Feb 2005 (PSF)
Python recipes (4591)
Frank Jeworrek-Schmidt's recipes (1)

Required Modules

Other Information and Tasks