How To Subscribe To Event Inside Module?

Hello,

I have python code in a module that contains an OnMouseUp event (in a Custom Button class)

In my main script, I want to subscribe an event to this module.CustomButton.OnMouseUp so that anytime the event fires from that button press, it runs the function inside my main script

It seems like one of those really easy things to do that I’m just stumped on and can’t figure out…

Any help is appreciated!

Here is the relevant code, please let me know if you need more context.

Main Script:

#! python3

from MyModule import CustomButton


def DoSomething():
    print("something done")


test_button = CustomButton()


def SubscribeToEvent():
    test_button.OnMouseUp += DoSomething


if __name__ == "__main__":
    SubscribeToEvent()

Module Script:

#! python3

import Eto.Forms
import Eto.Drawing
import Rhino


# Code for Custom Thumbnail Buttons
class CustomButton(Eto.Forms.Drawable):

    # Initialize CustomButton Class
    def __init__(self):
        super(CustomButton, self).__init__()

        # Variables Here

    def OnPaint(self, e):
        pass
        # Graphics Creation Here

    def OnMouseEnter(self, e):
        try:
            self._hover = True

            self.Invalidate()
        except Exception as ex:
            Rhino.RhinoApp.WriteLine(f"Error in OnMouseEnter: {ex}")

    def OnMouseLeave(self, e):
        try:
            self._hover = False
            self.Invalidate()
        except Exception as ex:
            Rhino.RhinoApp.WriteLine(f"Error in OnMouseLeave: {ex}")

    def OnMouseDown(self, e):
        try:
            pass
        except Exception as ex:
            Rhino.RhinoApp.WriteLine(f"Error in OnMouseDown: {ex}")

    def OnMouseUp(self, e):
        try:
            Rhino.RhinoApp.WriteLine("Mouse Click In Module")
            if e.Buttons == Eto.Forms.MouseButtons.Primary and self._hover:
                pass
                # Additional Logic As Needed

        except Exception as ex:
            Rhino.RhinoApp.WriteLine(f"Error in OnMouseUp: {ex}")

Main & Module Files:
20240814_Subcribe_To_Event_In_Module.py (245 Bytes)
20240814_Module_Event_Example_To_Subscribe_To.py (1.2 KB)

Thank you for your assistance!

def DoSomething(): needs to match the signature of the event it is trying to handle:

Try def DoSomething(sender, arg):

1 Like

Okay great, that makes sense. I’ll give it a try, thank you @eirannejad !

1 Like