{"id":3606,"date":"2021-04-22T10:21:09","date_gmt":"2021-04-22T10:21:09","guid":{"rendered":"http:\/\/truelogic.org\/wordpress\/?p=3606"},"modified":"2021-04-22T10:21:12","modified_gmt":"2021-04-22T10:21:12","slug":"preventing-interaction-in-wxvtkrenderwindowinteractor-py","status":"publish","type":"post","link":"https:\/\/truelogic.org\/wordpress\/2021\/04\/22\/preventing-interaction-in-wxvtkrenderwindowinteractor-py\/","title":{"rendered":"Preventing interaction in wxVTKRenderWindowInteractor.py"},"content":{"rendered":"\n<p>wxVTKRenderWindowInteractor.py is a class which allows a VTK rendering in a wxPython window. This class is available here: <a href=\"https:\/\/gitlab.kitware.com\/vtk\/vtk\/blob\/741fffbf6490c34228dfe437f330d854b2494adc\/Wrapping\/Python\/vtkmodules\/wx\/wxVTKRenderWindowInteractor.py\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"https:\/\/gitlab.kitware.com\/vtk\/vtk\/blob\/741fffbf6490c34228dfe437f330d854b2494adc\/Wrapping\/Python\/vtkmodules\/wx\/wxVTKRenderWindowInteractor.py (opens in a new tab)\">https:\/\/gitlab.kitware.com\/vtk\/vtk\/blob\/741fffbf6490c34228dfe437f330d854b2494adc\/Wrapping\/Python\/vtkmodules\/wx\/wxVTKRenderWindowInteractor.py<\/a><\/p>\n\n\n\n<p>One limitation which I found while using this is it if using a PyVista plotter, it does not follow the directives to stop the interactive camera by using <code>plotter.disable()<\/code><\/p>\n\n\n\n<p>I made a workaround by adding a kwards argument in the constructor <code>allow_interaction<\/code> which is set to True by default. <\/p>\n\n\n\n<p>This flag is checked in the BindEvents() method and the mouse events are not bound if the interaction is set to False. This simulates the action of the camera being non-interactive.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&quot;&quot;&quot;\n\nA VTK RenderWindowInteractor widget for wxPython.\n\nFind wxPython info at http:\/\/wxPython.org\n\nCreated by Prabhu Ramachandran, April 2002\nBased on wxVTKRenderWindow.py\n\nFixes and updates by Charl P. Botha 2003-2008\n\nUpdated to new wx namespace and some cleaning up by Andrea Gavana,\nDecember 2006\n\nAdded code to make the UI non-interactive by Amit Sengupta Apr 2021\n\n&quot;&quot;&quot;\n\n&quot;&quot;&quot;\nPlease see the example at the end of this file.\n\n----------------------------------------\nCreation:\n\n wxVTKRenderWindowInteractor(parent, ID, stereo=0, &#x5B;wx keywords]):\n\n You should create a wx.App(False) or some other wx.App subclass\n before creating the window.\n\nBehaviour:\n\n Uses __getattr__ to make the wxVTKRenderWindowInteractor behave just\n like a vtkGenericRenderWindowInteractor.\n\n----------------------------------------\n\n&quot;&quot;&quot;\n\n# import usual libraries\nimport math, os, sys\nimport wx\nimport vtk\n\n# a few configuration items, see what works best on your system\n\n# Use GLCanvas as base class instead of wx.Window.\n# This is sometimes necessary under wxGTK or the image is blank.\n# (in wxWindows 2.3.1 and earlier, the GLCanvas had scroll bars)\nbaseClass = wx.Window\n#if wx.Platform == &quot;__WXGTK__&quot;:\n#    import wx.glcanvas\n#   baseClass = wx.glcanvas.GLCanvas\n\n# Keep capturing mouse after mouse is dragged out of window\n# (in wxGTK 2.3.2 there is a bug that keeps this from working,\n# but it is only relevant in wxGTK if there are multiple windows)\n_useCapture = (wx.Platform == &quot;__WXMSW__&quot;)\n\n# end of configuration items\n\n\nclass EventTimer(wx.Timer):\n    &quot;&quot;&quot;Simple wx.Timer class.\n    &quot;&quot;&quot;\n\n    def __init__(self, iren):\n        &quot;&quot;&quot;Default class constructor.\n        @param iren: current render window\n        &quot;&quot;&quot;\n        wx.Timer.__init__(self)\n        self.iren = iren\n\n\n    def Notify(self):\n        &quot;&quot;&quot; The timer has expired.\n        &quot;&quot;&quot;\n        self.iren.TimerEvent()\n\n\nclass wxVTKRenderWindowInteractor(baseClass):\n    &quot;&quot;&quot;\n    A wxRenderWindow for wxPython.\n    Use GetRenderWindow() to get the vtkRenderWindow.\n    Create with the keyword stereo=1 in order to\n    generate a stereo-capable window.\n    &quot;&quot;&quot;\n\n    # class variable that can also be used to request instances that use\n    # stereo; this is overridden by the stereo=1\/0 parameter.  If you set\n    # it to True, the NEXT instantiated object will attempt to allocate a\n    # stereo visual.  E.g.:\n    # wxVTKRenderWindowInteractor.USE_STEREO = True\n    # myRWI = wxVTKRenderWindowInteractor(parent, -1)\n    USE_STEREO = False\n\n    def __init__(self, parent, ID, *args, **kw):\n        &quot;&quot;&quot;Default class constructor.\n        @param parent: parent window\n        @param ID: window id\n        @param **kw: wxPython keywords (position, size, style) plus the\n        &#039;stereo&#039; keyword\n        &quot;&quot;&quot;\n        # private attributes\n        self.__RenderWhenDisabled = 0\n\n        # First do special handling of some keywords:\n        # stereo, position, size, width, height, style\n\n        try:\n            self._allowInteraction = bool(kw&#x5B;&#039;allow_interaction&#039;])\n            del kw&#x5B;&#039;allow_interaction&#039;]\n        except KeyError:\n            self._allowInteraction = True\n\n        try:\n            stereo = bool(kw&#x5B;&#039;stereo&#039;])\n            del kw&#x5B;&#039;stereo&#039;]\n        except KeyError:\n            stereo = False\n\n        try:\n            position = kw&#x5B;&#039;position&#039;]\n            del kw&#x5B;&#039;position&#039;]\n        except KeyError:\n            position = wx.DefaultPosition\n\n        try:\n            size = kw&#x5B;&#039;size&#039;]\n            del kw&#x5B;&#039;size&#039;]\n        except KeyError:\n            try:\n                size = parent.GetSize()\n            except AttributeError:\n                size = wx.DefaultSize\n\n        # wx.WANTS_CHARS says to give us e.g. TAB\n        # wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK\n        style = wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE\n\n        try:\n            style = style | kw&#x5B;&#039;style&#039;]\n            del kw&#x5B;&#039;style&#039;]\n        except KeyError:\n            pass\n\n        # the enclosing frame must be shown under GTK or the windows\n        #  don&#039;t connect together properly\n        if wx.Platform != &#039;__WXMSW__&#039;:\n            l = &#x5B;]\n            p = parent\n            while p: # make a list of all parents\n                l.append(p)\n                p = p.GetParent()\n            l.reverse() # sort list into descending order\n            for p in l:\n                p.Show(1)\n\n        if baseClass.__name__ == &#039;GLCanvas&#039;:\n            # code added by cpbotha to enable stereo and double\n            # buffering correctly where the user requests this; remember\n            # that the glXContext in this case is NOT allocated by VTK,\n            # but by WX, hence all of this.\n\n            # Initialize GLCanvas with correct attriblist\n            attribList = &#x5B;wx.glcanvas.WX_GL_RGBA,\n                          wx.glcanvas.WX_GL_MIN_RED, 1,\n                          wx.glcanvas.WX_GL_MIN_GREEN, 1,\n                          wx.glcanvas.WX_GL_MIN_BLUE, 1,\n                          wx.glcanvas.WX_GL_DEPTH_SIZE, 16,\n                          wx.glcanvas.WX_GL_DOUBLEBUFFER]\n            if stereo:\n                attribList.append(wx.glcanvas.WX_GL_STEREO)\n\n            try:\n                baseClass.__init__(self, parent, ID, pos=position, size=size,\n                                   style=style,\n                                   attribList=attribList)\n                 \n            except wx.PyAssertionError:\n                # visual couldn&#039;t be allocated, so we go back to default\n                baseClass.__init__(self, parent, ID, pos=position, size=size,\n                                   style=style)\n                if stereo:\n                    # and make sure everyone knows that the stereo\n                    # visual wasn&#039;t set.\n                    stereo = 0\n\n        else:\n            baseClass.__init__(self, parent, ID, pos=position, size=size,\n                               style=style)\n\n        # create the RenderWindow and initialize it\n        self._Iren = vtk.vtkGenericRenderWindowInteractor()\n        self._Iren.SetRenderWindow( vtk.vtkRenderWindow() )\n        self._Iren.AddObserver(&#039;CreateTimerEvent&#039;, self.CreateTimer)\n        self._Iren.AddObserver(&#039;DestroyTimerEvent&#039;, self.DestroyTimer)\n        self._Iren.GetRenderWindow().AddObserver(&#039;CursorChangedEvent&#039;,\n                                                 self.CursorChangedEvent)\n\n        try:\n            self._Iren.GetRenderWindow().SetSize(size.width, size.height)\n        except AttributeError:\n            self._Iren.GetRenderWindow().SetSize(size&#x5B;0], size&#x5B;1])\n\n        if stereo:\n            self._Iren.GetRenderWindow().StereoCapableWindowOn()\n            self._Iren.GetRenderWindow().SetStereoTypeToCrystalEyes()\n\n        self.__handle = None\n\n        self.BindEvents()\n\n        # with this, we can make sure that the reparenting logic in\n        # Render() isn&#039;t called before the first OnPaint() has\n        # successfully been run (and set up the VTK\/WX display links)\n        self.__has_painted = False\n\n        # set when we have captured the mouse.\n        self._own_mouse = False\n        # used to store WHICH mouse button led to mouse capture\n        self._mouse_capture_button = 0\n\n        # A mapping for cursor changes.\n        self._cursor_map = {0: wx.CURSOR_ARROW, # VTK_CURSOR_DEFAULT\n                            1: wx.CURSOR_ARROW, # VTK_CURSOR_ARROW\n                            2: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZENE\n                            3: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZENWSE\n                            4: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZESW\n                            5: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZESE\n                            6: wx.CURSOR_SIZENS, # VTK_CURSOR_SIZENS\n                            7: wx.CURSOR_SIZEWE, # VTK_CURSOR_SIZEWE\n                            8: wx.CURSOR_SIZING, # VTK_CURSOR_SIZEALL\n                            9: wx.CURSOR_HAND, # VTK_CURSOR_HAND\n                            10: wx.CURSOR_CROSS, # VTK_CURSOR_CROSSHAIR\n                           }\n\n    def BindEvents(self):\n        &quot;&quot;&quot;Binds all the necessary events for navigation, sizing,\n        drawing.\n        &quot;&quot;&quot;\n        # refresh window by doing a Render\n        self.Bind(wx.EVT_PAINT, self.OnPaint)\n        # turn off background erase to reduce flicker\n        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)\n\n        # Bind the events to the event converters\n        if self._allowInteraction :\n            self.Bind(wx.EVT_RIGHT_DOWN, self.OnButtonDown)\n            self.Bind(wx.EVT_LEFT_DOWN, self.OnButtonDown)\n            self.Bind(wx.EVT_MIDDLE_DOWN, self.OnButtonDown)\n            self.Bind(wx.EVT_RIGHT_UP, self.OnButtonUp)\n            self.Bind(wx.EVT_LEFT_UP, self.OnButtonUp)\n            self.Bind(wx.EVT_MIDDLE_UP, self.OnButtonUp)\n            self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)\n            self.Bind(wx.EVT_MOTION, self.OnMotion)\n\n        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)\n        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)\n\n        # If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions\n        # of all characters are always returned.  EVT_CHAR also performs\n        # other necessary keyboard-dependent translations.\n        self.Bind(wx.EVT_CHAR, self.OnKeyDown)\n        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)\n\n        self.Bind(wx.EVT_SIZE, self.OnSize)\n\n        # the wx 2.8.7.1 documentation states that you HAVE to handle\n        # this event if you make use of CaptureMouse, which we do.\n        if _useCapture and hasattr(wx, &#039;EVT_MOUSE_CAPTURE_LOST&#039;):\n            self.Bind(wx.EVT_MOUSE_CAPTURE_LOST,\n                    self.OnMouseCaptureLost)\n\n\n    def __getattr__(self, attr):\n        &quot;&quot;&quot;Makes the object behave like a\n        vtkGenericRenderWindowInteractor.\n        &quot;&quot;&quot;\n        if attr == &#039;__vtk__&#039;:\n            return lambda t=self._Iren: t\n        elif hasattr(self._Iren, attr):\n            return getattr(self._Iren, attr)\n        else:\n            raise AttributeError(self.__class__.__name__ +\n                  &quot; has no attribute named &quot; + attr)\n\n    def CreateTimer(self, obj, evt):\n        &quot;&quot;&quot; Creates a timer.\n        &quot;&quot;&quot;\n        self._timer = EventTimer(self)\n        #self._timer.Start(10, True)\n        self._timer.Start(1, True)\n\n    def DestroyTimer(self, obj, evt):\n        &quot;&quot;&quot;The timer is a one shot timer so will expire automatically.\n        &quot;&quot;&quot;\n        return 1\n\n    def _CursorChangedEvent(self, obj, evt):\n        &quot;&quot;&quot;Change the wx cursor if the renderwindow&#039;s cursor was\n        changed.\n        &quot;&quot;&quot;\n        cur = self._cursor_map&#x5B;obj.GetCurrentCursor()]\n        c = wx.StockCursor(cur)\n        self.SetCursor(c)\n\n    def CursorChangedEvent(self, obj, evt):\n        &quot;&quot;&quot;Called when the CursorChangedEvent fires on the render\n        window.&quot;&quot;&quot;\n        # This indirection is needed since when the event fires, the\n        # current cursor is not yet set so we defer this by which time\n        # the current cursor should have been set.\n        wx.CallAfter(self._CursorChangedEvent, obj, evt)\n\n    def HideCursor(self):\n        &quot;&quot;&quot;Hides the cursor.&quot;&quot;&quot;\n        c = wx.StockCursor(wx.CURSOR_BLANK)\n        self.SetCursor(c)\n\n    def ShowCursor(self):\n        &quot;&quot;&quot;Shows the cursor.&quot;&quot;&quot;\n        rw = self._Iren.GetRenderWindow()\n        cur = self._cursor_map&#x5B;rw.GetCurrentCursor()]\n        c = wx.StockCursor(cur)\n        self.SetCursor(c)\n\n    def GetDisplayId(self):\n        &quot;&quot;&quot;Function to get X11 Display ID from WX and return it in a format\n        that can be used by VTK Python.\n\n        We query the X11 Display with a new call that was added in wxPython\n        2.6.0.1.  The call returns a SWIG object which we can query for the\n        address and subsequently turn into an old-style SWIG-mangled string\n        representation to pass to VTK.\n        &quot;&quot;&quot;\n        d = None\n\n        try:\n            d = wx.GetXDisplay()\n\n        except AttributeError:\n            # wx.GetXDisplay was added by Robin Dunn in wxPython 2.6.0.1\n            # if it&#039;s not available, we can&#039;t pass it.  In general,\n            # things will still work; on some setups, it&#039;ll break.\n            pass\n\n        else:\n            # wx returns None on platforms where wx.GetXDisplay is not relevant\n            if d:\n                d = hex(d)\n                # On wxPython-2.6.3.2 and above there is no leading &#039;0x&#039;.\n                if not d.startswith(&#039;0x&#039;):\n                    d = &#039;0x&#039; + d\n\n                # VTK wants it as: _xxxxxxxx_p_void (SWIG pointer)\n                d = &#039;_%s_%s\\0&#039; % (d&#x5B;2:], &#039;p_void&#039;)\n\n        return d\n\n    def OnMouseCaptureLost(self, event):\n        &quot;&quot;&quot;This is signalled when we lose mouse capture due to an\n        external event, such as when a dialog box is shown.  See the\n        wx documentation.\n        &quot;&quot;&quot;\n\n        # the documentation seems to imply that by this time we&#039;ve\n        # already lost capture.  I have to assume that we don&#039;t need\n        # to call ReleaseMouse ourselves.\n        if _useCapture and self._own_mouse:\n            self._own_mouse = False\n\n    def OnPaint(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_PAINT event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # wx should continue event processing after this handler.\n        # We call this BEFORE Render(), so that if Render() raises\n        # an exception, wx doesn&#039;t re-call OnPaint repeatedly.\n        event.Skip()\n\n        dc = wx.PaintDC(self)\n\n        # make sure the RenderWindow is sized correctly\n        self._Iren.GetRenderWindow().SetSize(self.GetSize())\n\n        # Tell the RenderWindow to render inside the wx.Window.\n        if not self.__handle:\n\n            # on relevant platforms, set the X11 Display ID\n            d = self.GetDisplayId()\n            if d and self.__has_painted:\n                self._Iren.GetRenderWindow().SetDisplayId(d)\n\n            # store the handle\n            self.__handle = self.GetHandle()\n            # and give it to VTK\n            self._Iren.GetRenderWindow().SetWindowInfo(str(self.__handle))\n\n            # now that we&#039;ve painted once, the Render() reparenting logic\n            # is safe\n            self.__has_painted = True\n\n        self.Render()\n\n    def OnSize(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_SIZE event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue (we call this before the\n        # Render(), in case it raises an exception)\n        event.Skip()\n\n        try:\n            width, height = event.GetSize()\n        except:\n            width = event.GetSize().width\n            height = event.GetSize().height\n        self._Iren.SetSize(width, height)\n        self._Iren.ConfigureEvent()\n\n        # this will check for __handle\n        self.Render()\n\n    def OnMotion(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_MOTION event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        # we call this early in case any of the VTK code raises an\n        # exception.\n        event.Skip()\n\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            event.ControlDown(),\n                                            event.ShiftDown(),\n                                            chr(0), 0, None)\n        self._Iren.MouseMoveEvent()\n\n    def OnEnter(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_ENTER_WINDOW event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            event.ControlDown(),\n              event.ShiftDown(),\n              chr(0), 0, None)\n        self._Iren.EnterEvent()\n\n\n    def OnLeave(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_LEAVE_WINDOW event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            event.ControlDown(),\n              event.ShiftDown(),\n              chr(0), 0, None)\n        self._Iren.LeaveEvent()\n\n\n    def OnButtonDown(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_LEFT\/RIGHT\/MIDDLE_DOWN events for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # allow wx event processing to continue\n        # on wxPython 2.6.0.1, omitting this will cause problems with\n        # the initial focus, resulting in the wxVTKRWI ignoring keypresses\n        # until we focus elsewhere and then refocus the wxVTKRWI frame\n        # we do it this early in case any of the following VTK code\n        # raises an exception.\n        event.Skip()\n\n        ctrl, shift = event.ControlDown(), event.ShiftDown()\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            ctrl, shift, chr(0), 0, None)\n\n        button = 0\n        if event.RightDown():\n            self._Iren.RightButtonPressEvent()\n            button = &#039;Right&#039;\n        elif event.LeftDown():\n            self._Iren.LeftButtonPressEvent()\n            button = &#039;Left&#039;\n        elif event.MiddleDown():\n            self._Iren.MiddleButtonPressEvent()\n            button = &#039;Middle&#039;\n\n        # save the button and capture mouse until the button is released\n        # we only capture the mouse if it hasn&#039;t already been captured\n        if _useCapture and not self._own_mouse:\n            self._own_mouse = True\n            self._mouse_capture_button = button\n            self.CaptureMouse()\n\n\n    def OnButtonUp(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_LEFT\/RIGHT\/MIDDLE_UP events for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        button = 0\n        if event.RightUp():\n            button = &#039;Right&#039;\n        elif event.LeftUp():\n            button = &#039;Left&#039;\n        elif event.MiddleUp():\n            button = &#039;Middle&#039;\n\n        # if the same button is released that captured the mouse, and\n        # we have the mouse, release it.\n        # (we need to get rid of this as soon as possible; if we don&#039;t\n        #  and one of the event handlers raises an exception, mouse\n        #  is never released.)\n        if _useCapture and self._own_mouse and \\\n                button==self._mouse_capture_button:\n            self.ReleaseMouse()\n            self._own_mouse = False\n\n        ctrl, shift = event.ControlDown(), event.ShiftDown()\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            ctrl, shift, chr(0), 0, None)\n\n        if button == &#039;Right&#039;:\n            self._Iren.RightButtonReleaseEvent()\n        elif button == &#039;Left&#039;:\n            self._Iren.LeftButtonReleaseEvent()\n        elif button == &#039;Middle&#039;:\n            self._Iren.MiddleButtonReleaseEvent()\n\n\n    def OnMouseWheel(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_MOUSEWHEEL event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        ctrl, shift = event.ControlDown(), event.ShiftDown()\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            ctrl, shift, chr(0), 0, None)\n        if event.GetWheelRotation() &gt; 0:\n            self._Iren.MouseWheelForwardEvent()\n        else:\n            self._Iren.MouseWheelBackwardEvent()\n\n\n    def OnKeyDown(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_KEY_DOWN event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        ctrl, shift = event.ControlDown(), event.ShiftDown()\n        keycode, keysym = event.GetKeyCode(), None\n        key = chr(0)\n        if keycode &lt; 256:\n            key = chr(keycode)\n\n        # wxPython 2.6.0.1 does not return a valid event.Get{X,Y}()\n        # for this event, so we use the cached position.\n        (x,y)= self._Iren.GetEventPosition()\n        self._Iren.SetEventInformation(x, y,\n                                       ctrl, shift, key, 0,\n                                       keysym)\n\n        self._Iren.KeyPressEvent()\n        self._Iren.CharEvent()\n\n\n    def OnKeyUp(self,event):\n        &quot;&quot;&quot;Handles the wx.EVT_KEY_UP event for\n        wxVTKRenderWindowInteractor.\n        &quot;&quot;&quot;\n\n        # event processing should continue\n        event.Skip()\n\n        ctrl, shift = event.ControlDown(), event.ShiftDown()\n        keycode, keysym = event.GetKeyCode(), None\n        key = chr(0)\n        if keycode &lt; 256:\n            key = chr(keycode)\n\n        self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),\n                                            ctrl, shift, key, 0,\n                                            keysym)\n        self._Iren.KeyReleaseEvent()\n\n\n    def GetRenderWindow(self):\n        &quot;&quot;&quot;Returns the render window (vtkRenderWindow).\n        &quot;&quot;&quot;\n        return self._Iren.GetRenderWindow()\n\n    def Render(self):\n        &quot;&quot;&quot;Actually renders the VTK scene on screen.\n        &quot;&quot;&quot;\n        RenderAllowed = 1\n\n        if not self.__RenderWhenDisabled:\n            # the user doesn&#039;t want us to render when the toplevel frame\n            # is disabled - first find the top level parent\n            topParent = wx.GetTopLevelParent(self)\n            if topParent:\n                # if it exists, check whether it&#039;s enabled\n                # if it&#039;s not enabeld, RenderAllowed will be false\n                RenderAllowed = topParent.IsEnabled()\n\n        if RenderAllowed:\n            if self.__handle and self.__handle == self.GetHandle():\n                self._Iren.GetRenderWindow().Render()\n\n            elif self.GetHandle() and self.__has_painted:\n                # this means the user has reparented us; let&#039;s adapt to the\n                # new situation by doing the WindowRemap dance\n                self._Iren.GetRenderWindow().SetNextWindowInfo(\n                    str(self.GetHandle()))\n\n                # make sure the DisplayId is also set correctly\n                d = self.GetDisplayId()\n                if d:\n                    self._Iren.GetRenderWindow().SetDisplayId(d)\n\n                # do the actual remap with the new parent information\n                self._Iren.GetRenderWindow().WindowRemap()\n\n                # store the new situation\n                self.__handle = self.GetHandle()\n                self._Iren.GetRenderWindow().Render()\n\n    def SetRenderWhenDisabled(self, newValue):\n        &quot;&quot;&quot;Change value of __RenderWhenDisabled ivar.\n\n        If __RenderWhenDisabled is false (the default), this widget will not\n        call Render() on the RenderWindow if the top level frame (i.e. the\n        containing frame) has been disabled.\n\n        This prevents recursive rendering during wx.SafeYield() calls.\n        wx.SafeYield() can be called during the ProgressMethod() callback of\n        a VTK object to have progress bars and other GUI elements updated -\n        it does this by disabling all windows (disallowing user-input to\n        prevent re-entrancy of code) and then handling all outstanding\n        GUI events.\n\n        However, this often triggers an OnPaint() method for wxVTKRWIs,\n        resulting in a Render(), resulting in Update() being called whilst\n        still in progress.\n        &quot;&quot;&quot;\n        self.__RenderWhenDisabled = bool(newValue)\n\n\n#--------------------------------------------------------------------\ndef wxVTKRenderWindowInteractorConeExample():\n    &quot;&quot;&quot;Like it says, just a simple example\n    &quot;&quot;&quot;\n    # every wx app needs an app\n    app = wx.App(False)\n\n    # create the top-level frame, sizer and wxVTKRWI\n    frame = wx.Frame(None, -1, &quot;wxVTKRenderWindowInteractor&quot;, size=(400,400))\n    widget = wxVTKRenderWindowInteractor(frame, -1)\n    sizer = wx.BoxSizer(wx.VERTICAL)\n    sizer.Add(widget, 1, wx.EXPAND)\n    frame.SetSizer(sizer)\n    frame.Layout()\n\n    # It would be more correct (API-wise) to call widget.Initialize() and\n    # widget.Start() here, but Initialize() calls RenderWindow.Render().\n    # That Render() call will get through before we can setup the\n    # RenderWindow() to render via the wxWidgets-created context; this\n    # causes flashing on some platforms and downright breaks things on\n    # other platforms.  Instead, we call widget.Enable().  This means\n    # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE,\n    # that doesn&#039;t matter.\n    widget.Enable(1)\n\n    widget.AddObserver(&quot;ExitEvent&quot;, lambda o,e,f=frame: f.Close())\n\n    ren = vtk.vtkRenderer()\n    widget.GetRenderWindow().AddRenderer(ren)\n\n    cone = vtk.vtkConeSource()\n    cone.SetResolution(8)\n\n    coneMapper = vtk.vtkPolyDataMapper()\n    coneMapper.SetInputConnection(cone.GetOutputPort())\n\n    coneActor = vtk.vtkActor()\n    coneActor.SetMapper(coneMapper)\n\n    ren.AddActor(coneActor)\n\n    # show the window\n    frame.Show()\n\n    app.MainLoop()\n\nif __name__ == &quot;__main__&quot;:\n    wxVTKRenderWindowInteractorConeExample()\n\n<\/pre><\/div>\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>wxVTKRenderWindowInteractor.py is a class which allows a VTK rendering in a wxPython window. This class is available here: https:\/\/gitlab.kitware.com\/vtk\/vtk\/blob\/741fffbf6490c34228dfe437f330d854b2494adc\/Wrapping\/Python\/vtkmodules\/wx\/wxVTKRenderWindowInteractor.py One limitation which I found while <a class=\"mh-excerpt-more\" href=\"https:\/\/truelogic.org\/wordpress\/2021\/04\/22\/preventing-interaction-in-wxvtkrenderwindowinteractor-py\/\" title=\"Preventing interaction in wxVTKRenderWindowInteractor.py\">[&#8230;]<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":3610,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[297],"tags":[],"class_list":["post-3606","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/3606","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/comments?post=3606"}],"version-history":[{"count":3,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/3606\/revisions"}],"predecessor-version":[{"id":3609,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/posts\/3606\/revisions\/3609"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media\/3610"}],"wp:attachment":[{"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/media?parent=3606"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/categories?post=3606"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/truelogic.org\/wordpress\/wp-json\/wp\/v2\/tags?post=3606"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}