Mar-27-2022, 04:58 PM
This does not work:
It is easy to tie events in your window to external logic. When reading about GUI programming you see this separation of responsibility. MVC, MVP, MVVM. In all of these you have something that represents data and state, something that displays data and state, and some kind of glue layer that ties the two together.
In this example I am just going to steal an after() event from the GUI and use it to periodically update my logic and presentation. This is not a great example. My entire model consists of time.time(). But hopefully it demonstrates the idea.
if __name__ == '__main__': app = Window() def trace(*event): print("app.couter in main", app.count.get()) app.count.trace_add("write", trace) app.after(1000, app.counter) app.mainloop()If there was any way to interact with the window you would see that it ignores mouse and keyboard events. You need to periodically call update, and that is usually done by calling mainloop().
It is easy to tie events in your window to external logic. When reading about GUI programming you see this separation of responsibility. MVC, MVP, MVVM. In all of these you have something that represents data and state, something that displays data and state, and some kind of glue layer that ties the two together.
In this example I am just going to steal an after() event from the GUI and use it to periodically update my logic and presentation. This is not a great example. My entire model consists of time.time(). But hopefully it demonstrates the idea.
import time import tkinter as tk class Glue(): def __init__(self, label): self.label = label self.start_time = time.time() self.label.after(1000, self.update) def update(self): self.label['text'] = str(time.time() - self.start_time) self.label.after(1000, self.update) class MainWindow(tk.Tk): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.count = 1 self.label = tk.Label(self, text='Hello World') self.label.pack() tk.Button(self, text="Press to stop", command=quit).pack() if __name__ == '__main__': app = MainWindow() Glue(app.label) # <- The glue that ties model and presentation app.mainloop()I timed my update to a timer in this example, but you can use any event.