[Python] Is initializing the model class in an MVC app in python necessary?

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am using this template to create a GUI that loads some data, does various stuff to it, visualize it, and then saves it.

    In the template the Model class has an init method, where on start up some initial "email address" is passed to it and this gets updated by the GUI entry.

    I dont need an initial variable. There is a button (in class View) that loads my data (using a function in class Controller). The data is "set" in Model (I think) and when I click another button (example, to plot data), View passes Model.data to another function in class Controller to plot it.

    So I commented out the init part of the model class.

    This works. But pycharm warns me that instance attribute "data" is defined outside of init. And given that the template I was using also instantiated its variable, I want to know if what I am doing is going to produce problems somewhere.

    Here is my code:

    import tkinter as tk
    from tkinter import ttk

    class Model:
    # def __init__(self):
    # self.data = []

    @property
    def data(self):
    return self.__data
    @data.setter
    def data(self, value):
    self.__data = value

    class View(ttk.Frame):
    def __init__(self, parent, model):
    super().__init__(parent)
    self.model = model

    # create widgets
    self.get_data_button = ttk.Button(self, text="load data", command=self.load_data_clicked)
    self.get_data_button.grid(row=2, column=3, padx=10)
    self.check_data_button = ttk.Button(self, text="plot avg data", command=self.check_data_clicked)
    self.check_data_button.grid(row=3, column=3, padx=10)



    # set the controller
    self.controller = None

    def set_controller(self, controller):
    self.controller = controller

    def load_data_clicked(self):
    if self.controller:
    self.controller.load_hdf5()


    def check_data_clicked(self):
    if self.controller:
    self.controller.check_avg_data(self.model.data)


    class Controller:

    def __init__(self, model, view):

    self.model = model

    self.view = view



    def load_hdf5(self):

    #gets data


    def check_avg_data(self, data):

    plot(data)





    class App(tk.Tk):

    def __init__(self):

    super().__init__()



    self.title('Tkinter MVC Demo')



    # create a model

    model = Model()



    # create a view and place it on the root window

    view = View(self, model)

    view.grid(row=0, column=0, padx=10, pady=10)



    # create a controller

    controller = Controller(model, view)



    # set the controller to view

    view.set_controller(controller)




    if __name__ == '__main__':
 app = App()
 app.mainloop()

    Continue reading...

Compartilhe esta Página