My problem is the following. Coming from a web background, I did not problems to do this, but in a Python desktop application I can´t really see what is the best way to organize the code according to a MVC pattern.
I want to create a window that according to user input, when a button is pressed, it shows similar entries that are available in the database. The window is my view.
So basically these are the relations:
1) Communication controller --> view
The controller has an instance of the view, and can use its exposed methods, as for example view.show_data(). I think this is the way to go.
# Controller
my_view = View()
...
my_view.show_data(whatever_data)
2) Communication view --> controller
When the user inserts some text, a method in the controller has to be fired so that it can ask the model for the necessary data in the database. The problem is that I don't know what is the best way for the view to tell the controller that it has to fire that very method.
My first idea is to pass a reference of the controller to the view, and bind the events on the view, something like this:
# Controller
my_view = View(self)
my_model = Model()
...
def on_user_input(self):
# process the input
user_input = ...
self.my_model.method_to_get_info(user_input)
And the view:
# View
def __init__(self, controller):
self.controller_reference = controller
self.launch_gui()
self.config_binds()
def launch_gui(self):
# ... configure all the GUI itself
self.button = ...
def config_binds(self):
self.button.Bind(wx.EVT_BUTTON, self.controller_reference.on_user_input())
But I think this "closed circle" relation is not a very clean solution. The view is referenced in the controller, and the controller in the view. I think it creates a tight relationship between the view and the controller.
What´s the way to do this?
The view is supposed to fire events. Normally you are not sending events directly to the controller, but the the GUI's frameworks generic event handler. The events in question are typically such event like "a key has been pressed", and "somebody moved the mouse".
A more "higher-level" MVC as in your case, can very well let the parts know of each other. That you tell the view what object is it's controller is perfectly fine. The important part is that all parts are using a well-defined interface, so that the parts are exchangeable.
As you see, this is quite different from the common web concept of model-view-controller which really isn't model-view-controller at all, but a misnomer and should be called model-view-template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With