Python Forum
[Tkinter] Return a value to __main__
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Return a value to __main__
#6
This does not work:
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.
Reply


Messages In This Thread
Return a value to __main__ - by menator01 - Mar-27-2022, 03:58 AM
RE: Return a value to __main__ - by Coricoco_fr - Mar-27-2022, 06:54 AM
RE: Return a value to __main__ - by menator01 - Mar-27-2022, 07:08 AM
RE: Return a value to __main__ - by Coricoco_fr - Mar-27-2022, 07:52 AM
RE: Return a value to __main__ - by menator01 - Mar-27-2022, 08:06 AM
RE: Return a value to __main__ - by deanhystad - Mar-27-2022, 04:58 PM
RE: Return a value to __main__ - by menator01 - Mar-27-2022, 05:10 PM
RE: Return a value to __main__ - by deanhystad - Mar-27-2022, 05:29 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020