From fb8993531fcd3dba04354eb9169e06a963f9122e Mon Sep 17 00:00:00 2001 From: Xiaokang2022 <2951256653@qq.com> Date: Tue, 7 Jan 2025 23:44:40 +0800 Subject: [PATCH] feat: Add the ability to use the with statement to the containers --- tkintertools/core/containers.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/tkintertools/core/containers.py b/tkintertools/core/containers.py index 48d9bbf4..901ce1f0 100644 --- a/tkintertools/core/containers.py +++ b/tkintertools/core/containers.py @@ -15,6 +15,7 @@ "Canvas", ] +import abc import collections.abc import functools import platform @@ -29,7 +30,21 @@ from . import configs, virtual -class Tk(tkinter.Tk): +class Misc(abc.ABC): + """An abstract miscellaneous class that implements some details.""" + + @abc.abstractmethod + def destroy(self) -> None: + """Destroy the object.""" + + def __enter__(self) -> typing_extensions.Self: + return self + + def __exit__(self, *args, **kwargs) -> None: + self.destroy() + + +class Tk(tkinter.Tk, Misc): """Main window. In general, there is only one main window. But after destroying it, another @@ -285,7 +300,7 @@ def wrapper() -> None: self.wm_protocol("WM_DELETE_WINDOW", wrapper) -class Toplevel(tkinter.Toplevel, Tk): +class Toplevel(tkinter.Toplevel, Tk, Misc): """Toplevel window. It can be used as a pop-up window, or it can be customized to put anything @@ -330,7 +345,7 @@ def destroy(self) -> None: return tkinter.Toplevel.destroy(self) -class Canvas(tkinter.Canvas): +class Canvas(tkinter.Canvas, Misc): """Main contrainer: Canvas. The parent widget of all virtual widgets is `Canvas`.