Display message when hovering over something with mouse cursor in Python

前端 未结 7 759
走了就别回头了
走了就别回头了 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:35

    You can refer to this- HoverClass

    It is exactly what you need. Nothing more, nothing less

    from Tkinter import *
    import re
    
    class HoverInfo(Menu):
        def __init__(self, parent, text, command=None):
           self._com = command
           Menu.__init__(self,parent, tearoff=0)
           if not isinstance(text, str):
              raise TypeError('Trying to initialise a Hover Menu with a non string type: ' + text.__class__.__name__)
           toktext=re.split('\n', text)
           for t in toktext:
              self.add_command(label = t)
           self._displayed=False
              self.master.bind("<Enter>",self.Display )
              self.master.bind("<Leave>",self.Remove )
    
        def __del__(self):
           self.master.unbind("<Enter>")
           self.master.unbind("<Leave>")
    
        def Display(self,event):
           if not self._displayed:
              self._displayed=True
              self.post(event.x_root, event.y_root)
           if self._com != None:
              self.master.unbind_all("<Return>")
              self.master.bind_all("<Return>", self.Click)
    
        def Remove(self, event):
         if self._displayed:
           self._displayed=False
           self.unpost()
         if self._com != None:
           self.unbind_all("<Return>")
    
        def Click(self, event):
           self._com()
    

    Example app using HoverInfo:

    from Tkinter import *
    from HoverInfo import HoverInfo
    class MyApp(Frame):
       def __init__(self, parent=None):
          Frame.__init__(self, parent)
          self.grid()
          self.lbl = Label(self, text='testing')
          self.lbl.grid()
    
          self.hover = HoverInfo(self, 'while hovering press return \n for an exciting msg', self.HelloWorld)
    
       def HelloWorld(self):
          print('Hello World')
    
    app = MyApp()
    app.master.title('test')
    app.mainloop()
    

    Screenshot:

    0 讨论(0)
提交回复
热议问题