Generating Tkinter GUIs from XMLApril 20th, 2011 • 1 Comment
Update: Please also see this post!
Sometimes I just need to develop some GUIs for testing and demos. For 80% cases I hack those kind of codes in Python so Tkinter is the best choice there. Pretty old school – I know 🙂
I would recommend Qt (using PySide or PyQT) for bigger GUI projects but for interoperability (Tkinter is part of the python download and runs everywhere :-)) issues and development speed I still choose Tkinter most of the time 🙂
What bugged me was the amount of code needed to create a simple GUI. Especially defining the GUI itself in a programming language is a pain – so why no split those things? Defining the GUI in an XML file and just use python to bind some operations behind it…An old blog post here describes this using Tkinter. So a peace of cake (esp. with Tkinter). I made some slight modifications (Support for frames in frames in frames etc.; grid geometry manager instead of pack manager; minor improvements on the XML side etc.) and now you can write a simple XML file like this:
<?xml version="1.0" encoding="UTF-8"?> <Frame> <LabelFrame text='Hello World' borderwidth='2' relief='groove' column='0' row='0' columnspan='2'> <Label text='Entry:' column='0' row='0'/> <Checkbutton name='check' text='checkbutton' column='1' row='0'/> <Entry name='entry' bg='gold' width='30' column='0' row='1' columnspan='2'/> </LabelFrame> <Button name='ok' text='OK' column='0' row='1'/> <Button name='cancel' text='Cancel' column='1' row='1'/> </Frame>
Write some simple python code so the GUI actually does something:
[...] xml_ui = TkFromXML() root = xml_ui.initialize('ui.xml', title = 'Some test gui...') # config vars for checkboxes etc. c = xml_ui.checkbox('check') def ok(): print xml_ui.entry('entry') print c.get() root.destroy() # add button behaviour xml_ui.button('ok', ok) xml_ui.button('cancel', root.destroy) root.mainloop()
So if ‘OK’ is pressed it will output the text inserted in the Box and the state of the Checkbox. Overall you get something like this:
Simple ain’t it? Comments more than welcome – I tend to release this on GitHub soon!