简体   繁体   English

Tkinter(python 2.7)| 确定其tk实例还是顶级实例

[英]Tkinter (python 2.7) | determine whether its tk instance or toplevel instance

Question

root1 = tk.Tk()
root2 = tk.Toplevel()

How can I determine from root1 and root2 whether the instance is tk or toplevel? 如何从root1root2确定实例是tk还是顶级?

My situation (for more context) 我的情况(更多情况)

I open two Tkinter (instance) window using the same myCustomGUI code. 我使用相同的myCustomGUI代码打开两个Tkinter(实例)窗口。

root = tk.Tk()
mainGUI = myCustomGUI(root)
mainGUI.handler.setLevel(logging.INFO)

root2 = tk.Toplevel()
secondGUI = myCustomGUI(root2)
secondGUI.handler.setLevel(logging.ERROR)

In the myCustomGUI class, I created a on_closing() function which runs when the user closes the window ( root.protocol("WM_DELETE_WINDOW", self.on_closing) ). myCustomGUI类中,我创建了一个on_closing()函数,该函数在用户关闭窗口时运行( root.protocol("WM_DELETE_WINDOW", self.on_closing) )。

In the said function on_closing() I want to have something like this: 在上述函数on_closing()我想要这样的东西:

def on_closing(self):
    if self.root is tk:
        self.root.quit()
        exit() # exit the whole program OR run some custom exit function
    else: # meaning self.root is Toplevel
        pass
    self.root.destroy()

In other words, when the instance is Toplevel then only destroy it and when the instance is the main window, then quit tkinter and exit the whole program. 换句话说,当实例为Toplevel时,仅销毁它;而当实例为主窗口时,则退出tkinter并退出整个程序。

Additional notes (NOT relevant to the question) 附加说明(与问题无关)

The purpose of opening two windows with the identical interface is to print debug info in one window and print important info in the other window, thus the interface is the same. 使用相同界面打开两个窗口的目的是在一个窗口中打印调试信息,并在另一个窗口中打印重要信息,因此界面是相同的。

The purpose I created a on_closing() function is because I have to remove the handler from logger . 我创建on_closing()函数的目的是因为我必须从logger删除处理程序。

The simplest solution is to ask tkinter what class the widget is -- not the python class but rather the internal tk class. 最简单的解决方案是询问tkinter窗口小部件是什么类-不是python类,而是内部tk类。 For the root window it will be Tk , and for a toplevel it will be Toplevel (unless you've explicitly changed it, which would be highly unusual). 对于根窗口,它将是Tk ,对于顶级窗口,它将是Toplevel (除非您已显式更改它,这是非常不寻常的)。

import tkinter as tk

class MyTop(tk.Toplevel):
    pass

root = tk.Tk()
top = tk.Toplevel(root)
mytop = MyTop(root)

assert(root.winfo_class() == "Tk")
assert(top.winfo_class() == "Toplevel")
assert(mytop.winfo_class() == "Toplevel")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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