Package: re-wx
A Python library for building modern declarative desktop applicationsOverviewre-wx is a library for building modern declarative desktop applications. It's built as a management layer on top of WXPython, which means you get all the goodness of a mature, native, cross-platform UI kit, wrapped up in a modern, React inspired API.What is it?It's a "virtualdom" for WX. You tell re-wx what you want to happen, and it'll do all the heavy lifting required to get WX to comply. It lets you focus on your state and business logic while leaving implentation details of WX's ancient API to re-wx.Say goodbye toDeep coupling of business logic to stateful widgetsAwkward auto-generated Python wrappers on old bloated C++ classesBeing forced to express UIs through low levelA.GetLayout().addChild(B)style plumbing codere-wx is:DeclarativeComponent Based100% compatible with all WXPython code basesRe-wx lets you build expressive, maintainable applications out of simple, testable, functions and components.Alpha Note:This is an early release and under active development. Expect a few bugs, feature gaps, and a bit of API instability. If you hit any snags, pop over to theissuesand let me know!InstallationThe latest stable version is available on PyPi.pip install re-wxDocumentationQuick StartMain ConceptsSupported ComponentsDebuggingGetting HelpQuick Start: RE-WX in 5 minutesre-wx has just a few core ideas: Elements, Components, and rendering. Everything else is achieved by combining these 3 ideas into larger and larger things.All re-wx application consists of just a few steps.define your application viewRendering  it to produce a wx objectkick off the wx Main Loop.Starting small: Hello Worldimportwxfromrewximportcreate_element,wsx,renderfromrewx.componentsimportStaticText,Frameif__name__=='__main__':app=wx.App()element=create_element(Frame,{'title':'My Cool Application','show':True},children=[create_element(StaticText,{'label':'Howdy, cool person!'})])frame=render(element,None)app.MainLoop()Run this and you'll see the output on the right. While not glamorous yet, it lets us explore several of the main ideas.At the heart of all re-wx applications is the humbleElement. We used the functioncreate_elementto build them. Applications are built by composing trees of these elements together into larger and larger composite structures.Here we've created two elements. A top-levelFrametype, which is required by WXPython, and then an innerStaticTextone, which displays text on the screen.Elements all consist of three pieces of data: 1. thetypeof the entity we want to render into the UI, 3. the properties ("props" from here on out) we want that entity to have, and 3. any children, which are themselves Elements.An important note is that Elements areplain data-- literally just a Python dict like this:{'type':Frame,'props':{'title':'My Cool Application','show':True,'children':[{'type':StaticText,'props':{'label':'Howdy, cool person!'}}]}Together, these elements make up the "virtualdom" used by re-wx uses to drive the underlying WXWidgets components. Creating an elementdoes notactually instantiate any WX elements. That job falls torenderrewx.renderis how we transform our tree of Elements into a live UI. It handles all of the lifting required to instantiate the WX Objects, associate them all together, and put them in the state specified by your tree. The output ofrenderis a WX Object, which in our example, is our top level frame.With the frame now happily created, we just have to tell WXPython to start its main loop, which will launch the GUI, and we've officially built our first re-wx app!A brief detour for WSX:Writing all thosecreate_elementstatements can get really tedious and creates a lot of visual noise which can make getting a feel for your UI's structure at a glance difficult. An alternative and recommended approach is to usewsx, which lets you use nested lists to express parent child relationships between components. It uses the exact same[type, props, *children]arguments ascreate_element, but with a terser more compact syntax. Here's the same example usingwsx.fromrewximportwsx...element=wsx([Frame,{'title':'My Cool Application','show':True},[StaticText,{'label':'Howdy, cool person!'}]])For the rest of this guide, we'll be using thewsxform, but you can usecreate_elementif you prefer.A Stateful componentComponents are how you store and manage state in re-wx.classClock(Component):def__init__(self,props):super().__init__(props)self.timer=Noneself.state={'time':datetime.datetime.now()}defcomponent_did_mount(self):self.timer=wx.Timer()self.timer.Notify=self.update_clockself.timer.Start(milliseconds=1000)defupdate_clock(self):self.set_state({'time':datetime.datetime.now()})defrender(self):returnwsx([c.Block,{},[c.StaticText,{'label':self.state['time'].strftime('%I:%M:%S'),'name':'ClockFace','foreground_color':'#51acebff','font':big_ol_font(),'proporton':1,'flag':wx.CENTER|wx.ALL,'border':60}]])if__name__=='__main__':app=wx.App()frame=wx.Frame(None,title='Clock')clock=render(create_element(Clock,{}),frame)frame.Show()app.MainLoop()Here we've setup a Component which keeps track of the current time and displays it nice and bold in the center of our frame.There's lot going on here, so we'll take if from the top!You define your own components by inheriting fromrewx.Component. This gives you access to all the lifecycle and state management options provided by the base class. You can checkout theMain Conceptsfor the full details of the life cycle methods.Components have a few notable methods:MethodUsage__init__This gets called when re-wx instantiates your class. This is where you specify your initial state. Note that this is calledbeforethe actual GUI elements are available. This method should be used only to initialize data, not deal with presentational concernsrenderThis is where you'll create your element tree which defines your UI.component_did_mountThis method is called once all of your Component's elements have been rendered and mounted onto a wx.Window. It's here that you can kick off any work which requires the GUI to be up and runningset_stateThis method is used update your components state and kick off a re-render of its visuals.Still just an elementYou use your component like any other Element we've encountered so far. Meaning, you don't instantiate it directly, you put in in your Element tree and let re-wx handle all the details.That's what we're doing down at the bottom of the file where we wire the app together. We create an Element from our Component just like normal:create_element(Clock, {})and pass it to our render function.if __name__ == '__main__':
    app = wx.App()
    frame = wx.Frame(None, title='Clock')
    clock = render(create_element(Clock, {}), frame)
    frame.Show()
    app.MainLoop()An ApplicationOur final example will pull it all together. It combines plain Elements, Components, and business logic into a complete application.defTodoList(props):returncreate_element(c.Block,{},children=[create_element(c.StaticText,{'label':f" *{item}"})foriteminprops['items']])classTodoApp(Component):def__init__(self,props):super().__init__(props)self.state={'items':['Groceries','Laundry'],'text':''}defhandle_change(self,event):self.set_state({**self.state,'text':event.String})defhandle_submit(self,event):self.set_state({'text':'','items':[*self.state['items'],self.state['text']]})defrender(self):returnwsx([c.Frame,{'title':'My First TODO app'},[c.Block,{'name':'main-content'},[c.StaticText,{'label':'What needs to be done?'}],[c.TextCtrl,{'value':self.state['text']}],[c.Button,{'label':'Add','on_click':self.handle_submit}],[c.StaticText,{'label':'TO DO:'}],[TodoList,{'items':self.state['items'],'on_click':self.handle_complete}]]])if__name__=='__main__':app=wx.App()frame=render(create_element(TodoApp,{}),None)frame.Show()app.MainLoop()Where to go from here?Checkout the docs folder for more detailed guides and walk throughsPhilosophyIt's a library first.re-wx is "just" a library,nota framework. Beacuse it's a library, you can use as much or as little of as you need. It requires no application-level total buy in like a framwork would. You don't have to do everything the "re-wx way. Further, the output from a re-wxrenderis a plain old WXPython component. Meaning, all re-wx componentsAREWX components, and thus require no special handling to integrate with your existing code base.It's intended to be symbiotic with WXPythonre-wx is not trying to be an general purpose abstraction over multiple backend UI kits. It's lofty goals begin and end with it being a way of making writing native, cross-platform UIs in WXPython easier. As such, it doesn't need reconcilers, or generic transactions, or any other abstraction related bloat. As a result, re-wx's core codebase is just a handful of files and can be understood in an afternoon.Given the symbiotic nature, practicality is favored over purity of abstraction. You'll mix and match WXPython code and re-wx code as needed. A good example of this is for transient dialogs (confirming actions, getting user selectsions, etc..). In React land, you'd traditionally have a modal in your core markup, and then conditionally toggle its visibility via state. However, in re-wx, you'll just use the dialog directly rather than embedding it in the markup and handling its lifecycle viais_openstyle state flags. This is practical to do because, unlike React in Javascript, WX handles managing the UI thread thus allowing us to block in place without any negative effects. Which enables writing straight forward in-line Dialog code.defhandle_choose_dir(self,event):dlg=wx.DirDialog(None)ifdlg.Show()==wx.ID_OK:self.setState({'directory':dlg.GetPath()})Compromises and caveats in the designWhile you'll program in a declarative style and enjoy the benefits that one-way data flows bring, a caveat is that not all components technically follow the unidirectional dataflow. The design of WX and the native APIs means that certain events are only firedafterinternal states have been updated. So, for components likewx.ComboBoxandwx.TextCtrl, handlers don't have a chance to operate until the widgets themseves have completed their work.The good news is that in practice, this is generally something you'll never notice or need to worry about. All updates are all done inside of a Freeze/Thaw transaction, thus hiding any visual quirks or flicker which may have come from re-wx forcing WX back into the state you specify rather than its own internally managed one.API Surface area:Only the most common attributes are currently managed by declarative props (basically, most of what falls underwx.Control). For example, specifics such asInsertionPoints inTextCtrls are considered out of scope for rewx.Refs act as a handy escape-hatch for when you need access to the full WX API. Be sure to checkout theComponet Docsfor the full list of supported props.Stubborn Widgets:Some WXPython widget, like the prefab RadioGroup, cannot have its number of options changed after creation. So, updating thechoicesprop will have no effect. Luckily, these components are few and far between, and usually have easy work arounds or alternatives. See theComponet Docsfor more info.Stuck? Need some help? Just have a question?Open an issuehere, or feel free to hit me up directly atme@chriskiehl.comand we'll get it sorted out!ContributingAll contributions are welcome! Just make sure you follow the Contributing Guidelines.Licensere-wx is MIT licensed.