ARTICLE AD BOX
I'd like to wrap my tkinter app within a child class to start and end a database connection when the app is started and closed or if it crashes. The connection will be used thoughout the app.
So my approach is to implement the context manager protocol (with-statement) for the child class. However, when executing within the "with" block the instance executes the __enter__() and after one line of print() code also the __exit__() routines. Within the with statement the instance app is None thus .mainloop() cannot be started.
I have no idea what my issue is. Alternatively, what would be the next cleanest way to implement this?
# -*- coding: utf-8 -*- import tkinter as tk class App(tk.Tk): def __init__(self): print('A: Initializing app...') tk.Tk.__init__(self) self.geometry('+%d+%d'%(0,64)) def __enter__(self): print('A: Opening DB connection...') def __exit__(self, exc_type, exc_val, exc_tb): print('A: Closing DB connection...') if __name__ == "__main__": print('Starting instance...') app=App() app.mainloop() print('Instace stopped') print('Starting with-statement ...') with App() as app: print('Starting loop...') app.mainloop() print('Exited')The output is:
Starting instance... A: Initializing app... Instace stopped Starting with-statement ... A: Initializing app... A: Opening DB connection... Starting loop... A: Closing DB connection... AttributeError: 'NoneType' object has no attribute 'mainloop'