embedding python in wxpython

Mike Driscoll kyosohma at gmail.com
Tue Dec 30 17:00:45 EST 2008


On Dec 30, 3:41 pm, Steve Holden <st... at holdenweb.com> wrote:
> 5lvqbw... at sneakemail.com wrote:
> > Hi, I've looked around for a way to allow a python console from within
> > a wxPython application, but have only found stuff on embedded/
> > extending python with C/C++ or wxWidgets in C++, but not wxPython.
>
> > Is this easy to do?  Can someone point me in the right direction?
>
> > Also, typically when you embed a scripting language into a larger
> > application, how do you get the console environment to share data with
> > the larger application?
>
> > For instance, if the application has some gui stuff (for example
> > clicking on a object and dragging it around), how do you get
> > "object.select(x,y)" to print out on the console, and vice-versa: the
> > object gets selected if the user types "object.select(x,y)"?
>
> > I'd like the console to be a bidirectional representation of what's
> > going on in the gui, plus a general purpose evaluation environment
> > where you can manipulate application data via some api which is
> > automatically exposed to the console when the application opens up.
>
> > I'm looking for high-level hints/strategies/directions.
>
> I seem to remember you can create your wxApp with an argument of True or
> False. One of those settings creates a window containing any output to
> sys.stderr, if I remember rightly.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

That's true...or you can just redirect stdout, which is what the demo
does. Here's one way to do it:

<code>
import sys
import wx

class RedirectText:
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "wxPython Redirect
Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,100),
                          style = wx.TE_MULTILINE|wx.TE_READONLY|
wx.HSCROLL)
        btn = wx.Button(panel, wx.ID_ANY, 'Push me!')
        self.Bind(wx.EVT_BUTTON, self.onButton, btn)

        # Add widgets to a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(log, 1, wx.ALL|wx.EXPAND, 5)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)

        # redirect text here
        redir=RedirectText(log)
        sys.stdout=redir

    def onButton(self, event):
        print "You pressed the button!"


# Run the program
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()
</code>

- Mike



More information about the Python-list mailing list