'MVC with tkinter?
I'm trying to do a simple flashcards game with tkinter with MVC pattern but I do not know how to connect the view with their controller...the problem is that I want to create more screens and controllers but at first is impossible to when you destroy the frame and create the instance of a new frame (View), you have to call the corresponding controller and pass it the instance of the view so that it can interact with it but I'm going crazy...
Is this approach wrong? How can I do MVC pattern in tkinter? How could I activate or deactivate the controller depending on the view I am on? I mean activate controller 1, view 1 is activated, switch to controller 2 and view 2 is activated...
Anybody have some ideas? Any idea is welcome.
I found some examples to switch frame with destroy()
method but that is not my approach:
My code
main.py
from manager import Manager
from controller.home_controller import HomeController
if _name_ == '_main_':
controller = HomeController()
manager = Manager(controller)
controller.set_manager(manager)
controller.switch_to_home()
manager.mainloop()
home_controller.py
from view.home_view import HomeView
class HomeController:
def _init_(self):
self.manager = None
def user_login(self, user_name, user_email, user_password):
print('Hola')
def set_manager(self, manager):
self.manager = manager
def switch_to_home(self):
self.manager.switch_view(HomeView)
def switch_to_login(self):
self.manager.switch_view(LoginView)
home_view.py
import tkinter as tk
class HomeView(tk.Frame):
def _init_(self, manager):
super()._init_()
self.manager = manager
self.config(padx=50, pady=50)
self.create_widgets()
def create_widgets(self):
self.register_button = tk.Button(self, text="Register", width=8, highlightthickness=0, command=...)
self.register_button.grid(row=0, column=0)
manager.py
import tkinter as tk
class Manager(tk.Tk):
def _init_(self, controller, *args, **kwargs):
super()._init_(*args, **kwargs)
self.title('FlashCards')
self.config(padx=50, pady=50)
# self.container = tk.Frame(self)
self.controller = controller
self.container = None
# self.switch_view(HomeView)
# self.controller.set_manager(self)
def switch_view(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self.container is not None:
self.container.destroy()
self.container = new_frame
self.container.pack(
side='top',
fill='both',
expand=True
)
self.container.grid_columnconfigure(1, weight=1)
self.container.grid_rowconfigure(1, weight=1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|