How to pass Model action to View button in Tkinter MVC?
If the button has no command, then nothing will ever happen.It needs to have a command, that calls a function of the controller.
Then, the controller will execute this command, either by communicating with the model, or by triggering another view.
Since the button is going to call a function of the controller, it needs to be aware of it.Let's assume that you passed it as parameter, and that you want the button to trigger controller.Action
, controller
being an (the?) instance of Controller
.
Here is how your view should look like:
class View(): def __init__(self, master, controller): self.master = master self.controller = controller b = Button(master, text='Hello', command=self.controller.Action()) b.pack()
Then, clicking on the button will result in a call to Action
.
You can use this in the controllers init() function:
self.view.b.bind("<Button>",self.action)
That way you don't have to use a command in the view.
I'm still trying to figure out how to do this for menubuttons... so this might be a bit of a struggle if it's new for you (like it is for me).
Edit:As requested, a small sample:
import tkinter as tk# Data stuffclass Model(): def __init__(self): pass # GUIclass View(): def __init__(self, master): self.master = master self.b = tk.Button(self.master, text="quit") self.b.pack()# Logic of the appclass Controller(): def __init__(self): self.root = tk.Tk() self.model=Model() self.view=View(self.root) self.view.b.bind("<Button>",self.action) self.run() def run(self): self.root.mainloop() def action(self,event): self.root.destroy()if __name__ == '__main__': c = Controller()