Python declarative
Francesco Bochicchio
bieffe62 at gmail.com
Fri Jan 17 09:22:11 EST 2014
Some time ago I played with Tkinter trying a more declarative way of coding the GUI building part and I come out with this:
top = Tk( 'top' ).add (
Frame( 'frame' ).add (
Pack( side = 'top' ),
Frame ( 'panel1' ).add (
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry ( 'entry' )
),
Frame( 'panel2' ).add (
Pack( side='left'),
Label ( 'label', text="Entry 2 : " ),
Entry( 'entry' )
),
Pack( side = 'bottom' ), # packing change
Button( 'button',
text='Click Me' ))
)
top.frame.button["command"] = functools.partial(button_cb, top)
top.realize().mainloop()
which, without changing the underlying plumbing, may also be written this way, which avoid nesting but still looks declarative-ish :
top = Tk( 'top' )
top.add( Frame( 'frame' ) )
top.frame.add (
Pack( side = 'top' ),
Frame ( 'panel1' ),
Frame( 'panel2' ),
Pack( side = 'bottom' ), # packing change
Button( 'button',
text='Click Me',
command = functools.partial(button_cb, top) ) )
top.frame.panel1.add(
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry ( 'entry' ) )
top.frame.panel2.add(
Pack( side='left'),
Label ( 'label', text="Entry 1 : " ),
Entry( 'entry' ) )
top.realize().mainloop()
The underlying plumbing for those two examples is just two classes amounting to about fifty lines of code, plus one-liner wrappers for each kind of widgets/geometry
This just to tell you that yes, with python you can write declarative-looking code ... if you don't mind parenthesis :-)
More information about the Python-list
mailing list