Correct abstraction for TK

Paul Rubin http
Tue Jul 3 03:50:52 EDT 2007


luke.hoersten at gmail.com writes:
> I'm looking for a good example of how to correctly abstract TK code
> from the rest of my program. I want to just get some user info and
> then get 4 values from the GUI. Right now I've written it OOP per the
> examples on python.org but it doesn't seem to be meshing very well
> with the rest of my project.

Simplest: just have gui operations call the application code.  The
application main loop is just the gui event loop.  Example (first tk
program I ever wrote, and one of my first python programs):

   http://www.nightsong.com/phr/python/calc.py

That might be enough for what you're doing.

Fancier: put gui in separate thread.  Be careful, it's not reentrant;
all communication with the application has to be through queues, sort
of like writing a miniature web server.  Most straightforward is to
pass tuples like (function, args, **kwargs) through the queues, where
the opposite end invokes the function on the arg list.  There are some
recipes in the Python cookbook for triggering the event loop on a
periodic timeout from inside tkinter.

See also "model-view-controller" for a more complex design approach
intended to separate the interface from the application logic.

Finally, consider total separation by embedding an http server in the
application, so the gui is a web browser and you write a web app.
It's often easier to code a simple html interface than to mess with
the damn Tk widgets and trying to get them to look decent on the
screen, plus it lets you easily put the client on a remote machine,
support multiple clients simultaneously, etc.



More information about the Python-list mailing list