简体   繁体   中英

tkinter: Validate existance of a root window / instance of Tk

I wanted to check if there is already an instance of Tk, to use my library that is built upon tkinter alongside with the original. The only indicator I have found is tkinter._default_root but at the same time I want to disable the support of default root . It appears to be a dilemma but following the tk.create to _tkinter_create_impl leads me to Tkpp_New C code with the form of:

    /* This is used to get the application class for Tk 4.1 and up */
    argv0 = (char*)PyMem_Malloc(strlen(className) + 1);
    if (!argv0) {
        PyErr_NoMemory();
        Py_DECREF(v);
        return NULL;
    }

But it relies on the className and the instance of Tk could be subclassed, so it seems unreliable to me. To be honest, I never wrote something in C, so I'm not entirely sure if this is really an option and worth to work it out.

So my question is: Is it possible to know if there is already an instance Tk in place?

Thanks to Bryan Oakley for pointing me to this answer . After thinking it through, this seems to be the only valid choice. Considerations:

  1. The name of the app or the class can be changed.
  2. Calling tkinter methods would instantly create an instance of Tk
  3. Tracing the __init__ method would rely on the order of imports and time they are set*
  4. override the standard lib is unreliable and can lead to confusing results.

*Traceprofile or Metaclasses takes away options for users

gc.get_objects shouldn't really slow down the program, cause there shouldn't be this much objects in the beginning of a GUI script. Please feel free to answer another approach, if there is another valid approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM