Ideal way to separate GUI and logic?
steve+comp.lang.python at pearwood.info
Sat Jul 13 13:43:25 CEST 2013
On Sat, 13 Jul 2013 04:07:21 -0700, fronagzen wrote:
> Well, I'm a newcome to Python, but I'm developing a program with a GUI
> in tkinter, and I'm wondering what is the best, 'most pythonic' way of
> doing this?
> I could, obviously, write a monolithic block of code.
> I can define the logic and the GUI as two separate classes and then call
> from those classes within a single script.
> Those are probably less than ideal.
> But how then do I separate out the logic and the GUI? Because the GUI
> needs to have commands defined for button presses and so forth, and
> those have to come from the logic section. Do I write the logic in a
> separate file and then import those to the GUI, and then run it there?
> Wouldn't it be better to have one file for the GUI, one for the logic,
> and then a third one that imports from both and then executes the app?
> How do I do that? (Examples would be nice, if possible.)
The important thing is that the application logic is separate from the
user interface. It doesn't matter whether than means "two functions in
the same module", or "two modules". Whether you decide to split your code
into two modules depends on how complex your code is.
For example, if you are writing a "Hello World" application, you would be
nuts to split this into two files.
=== cut ===
return "Hello, %s!" % name
if name is None:
name = raw_input("What is your name? ").strip()
=== cut ===
Only you know how big and complex your application is, so only you know
whether or not you should separate the GUI interface from the internal
logic. But, my guess is that for anything non-trivial, you probably
should have one main module handling the UI, and a second (and possibly
more) modules handling the implementation, plus at least one other module
More information about the Python-list