Indicate Mouseover Event (wxPython)

bumsfeld 0 Tallied Votes 2K Views Share

This short code shows how to indicate the mouse-over event on wxPython button, similar to the mouse-over in web pages. Button changes colour when mouse pointer is over its area.

# indicate mouseover action on wx.Button
# tested with Python24 and wxPython26   by  HAB

import wx

class MyFrame(wx.Frame):
    """Frame with Panel and one Button, inherits wx.Frame"""
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Move mouse over button',
                size=(350, 100))
        self.panel = wx.Panel(self)
        self.butn1 = wx.Button(self.panel, label="Press me", pos=(125, 15))
        # get original colour
        self.colour = self.butn1.GetBackgroundColour()
        self.butn1.Bind(wx.EVT_BUTTON, self.onButtonClick)
        self.butn1.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
        self.butn1.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)
        
    def onButtonClick(self, event):
        # do something ...
        self.panel.SetBackgroundColour('Yellow')
        self.panel.Refresh()
        
    def onMouseOver(self, event):
        # mouseover changes colour of button
        self.butn1.SetBackgroundColour('Green')
        event.Skip()
        
    def onMouseLeave(self, event):
        # mouse not over button, back to original colour
        self.butn1.SetBackgroundColour(self.colour)
        event.Skip()
        
    
# test it ...
if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MyFrame(parent=None, id=-1)
    frame.Show()
    app.MainLoop()