Display message when hovering over something with mouse cursor in Python

前端 未结 7 794
走了就别回头了
走了就别回头了 2020-12-01 10:57

I have a GUI made with TKinter in Python. I would like to be able to display a message when my mouse cursor goes, for example, on top of a label or button. The purpose of th

7条回答
  •  盖世英雄少女心
    2020-12-01 11:21

    I wanted to contribute to the answer of @squareRoot17 as he inspired me to shorten his code while providing the same functionality:

    import tkinter as tk
    
    class ToolTip(object):
        def __init__(self, widget, text):
            self.widget = widget
            self.text = text
    
            def enter(event):
                self.showTooltip()
            def leave(event):
                self.hideTooltip()
            widget.bind('', enter)
            widget.bind('', leave)
    
        def showTooltip(self):
            self.tooltipwindow = tw = tk.Toplevel(self.widget)
            tw.wm_overrideredirect(1) # window without border and no normal means of closing
            tw.wm_geometry("+{}+{}".format(self.widget.winfo_rootx(), self.widget.winfo_rooty()))
            label = tk.Label(tw, text = self.text, background = "#ffffe0", relief = 'solid', borderwidth = 1).pack()
    
        def hideTooltip(self):
            tw = self.tooltipwindow
            tw.destroy()
            self.tooltipwindow = None
    

    This class can then be imported and used as:

    import tkinter as tk
    from tooltip import ToolTip
    
    root = tk.Tk() 
    
    your_widget = tk.Button(root, text = "Hover me!")
    ToolTip(widget = your_widget, text = "Hover text!")
    
    root.mainloop()
    

提交回复
热议问题